global-object-factory
v1.0.0
Published
Global Object Factory for TypeScript - Lightweight dependency injection for legacy code
Maintainers
Readme
Global Object Factory for TypeScript
Lightweight dependency injection for legacy code. Replace 'new' with testable factories without major refactoring.
Introduction
ObjectFactory helps you make legacy code testable by replacing direct instantiation (new) with controllable factory functions. This enables dependency injection without requiring major architectural changes.
Quick Example
Replace direct instantiation with create() to make dependencies controllable:
// Before: Hard dependency
const emailService = new EmailService(connectionString);
// After: Testable dependency
import { create } from 'global-object-factory';
const emailService = create(EmailService)(connectionString);Now you can inject test doubles in your tests without changing production code:
import { setOne } from 'global-object-factory';
setOne(EmailService, mockEmailService);
// Next create(EmailService)() call returns mockEmailServiceInstallation
Add to your project:
npm install global-object-factoryOr with yarn:
yarn add global-object-factoryCore Components
Global Object Factory: Making Dependencies Testable
Use Case: Your legacy code creates dependencies with new, making it impossible to inject test doubles.
Solution: Replace new with create() to enable dependency injection without major refactoring.
Breaking Dependencies
Transform hard dependencies into testable code:
// Legacy code with hard dependency
class UserService {
processUser(id: number) {
const repo = new SqlRepository("server=prod;...");
const user = repo.getUser(id);
// ...
}
}
// Testable code using Global Object Factory
import { create } from 'global-object-factory';
class UserService {
processUser(id: number) {
const repo = create(SqlRepository)("server=prod;...");
const user = repo.getUser(id);
// ...
}
}In Tests
import { setOne, clearAll } from 'global-object-factory';
describe('UserService', () => {
afterEach(() => {
clearAll();
});
it('should process user successfully', () => {
// Setup
const mockRepo = new MockSqlRepository();
mockRepo.users.set(123, { name: 'John', email: '[email protected]' });
setOne(SqlRepository, mockRepo);
// Act
const service = new UserService();
const result = service.processUser(123);
// Assert
expect(result).toEqual({ name: 'John', email: '[email protected]' });
});
});Test Double Injection
Use setOne for single-use mocks or setAlways for persistent test doubles:
import { ObjectFactory, setOne, setAlways } from 'global-object-factory';
// Single-use test double (consumed after first use)
setOne(EmailService, mockEmailService);
// Persistent test double (used for all calls)
setAlways(DatabaseService, mockDatabaseService);
// setOne takes priority over setAlways
setAlways(MyService, alwaysService);
setOne(MyService, onceService);
const service1 = create(MyService)(); // Returns onceService
const service2 = create(MyService)(); // Returns alwaysServiceFactory Instance Usage
For more control, use ObjectFactory instances:
import { ObjectFactory } from 'global-object-factory';
describe('MyService', () => {
let factory: ObjectFactory;
beforeEach(() => {
factory = new ObjectFactory();
});
afterEach(() => {
factory.clearAll();
});
it('should use mock repository', () => {
// Setup
const mockRepo = new MockRepository();
factory.setOne(Repository, mockRepo);
// Act - your code calls create(Repository)() and gets mockRepo
const service = new MyService(factory);
const result = service.processData();
// Assert
expect(result).toEqual(expected);
});
});Global Singleton Pattern
Use the global singleton for convenience:
import { create, setOne, setAlways, clearAll } from 'global-object-factory';
// All functions use the global singleton
setAlways(EmailService, mockEmailService);
// Anywhere in your code
const service = create(EmailService)();
// Clean up in test teardown
afterEach(() => {
clearAll();
});Constructor Parameter Tracking
Implement IConstructorCalledWith to receive parameter information:
import { IConstructorCalledWith, ConstructorParameterInfo } from 'global-object-factory';
class TrackedService implements IConstructorCalledWith {
constructor(
public config: string,
public port: number
) {}
constructorCalledWith(params: ConstructorParameterInfo[]): void {
// params[0] = { index: 0, type: 'string', value: 'localhost' }
// params[1] = { index: 1, type: 'number', value: 8080 }
}
}
const service = create(TrackedService)('localhost', 8080);
// constructorCalledWith is automatically called with parameter detailsObject Registration
Register objects with IDs for clean test specifications:
const factory = new ObjectFactory();
// Complex configuration object
const dbConfig = {
host: 'localhost',
port: 5432,
database: 'testdb'
};
// Register with ID
factory.register(dbConfig, 'testDbConfig');
// Later retrieve by ID
const config = factory.getRegistered<DatabaseConfig>('testDbConfig');
// Auto-generate IDs if not provided
const obj1 = { value: 1 };
const id = factory.register(obj1); // Returns 'auto_1'Migration Examples
Before (Direct Instantiation)
class OrderProcessor {
processOrder(orderId: string) {
const db = new DatabaseConnection("prod-server");
const emailService = new EmailService("smtp.example.com", 587);
const order = db.getOrder(orderId);
if (order.status === 'pending') {
emailService.sendConfirmation(order.customerEmail);
}
}
}After (Using Global Object Factory)
import { create } from 'global-object-factory';
class OrderProcessor {
processOrder(orderId: string) {
const db = create(DatabaseConnection)("prod-server");
const emailService = create(EmailService)("smtp.example.com", 587);
const order = db.getOrder(orderId);
if (order.status === 'pending') {
emailService.sendConfirmation(order.customerEmail);
}
}
}In Tests
import { setOne, clearAll } from 'global-object-factory';
describe('OrderProcessor', () => {
afterEach(() => clearAll());
it('should send confirmation email for pending orders', () => {
// Arrange
const mockDb = new MockDatabase();
mockDb.setOrder('123', { status: 'pending', customerEmail: '[email protected]' });
const mockEmail = new MockEmailService();
setOne(DatabaseConnection, mockDb);
setOne(EmailService, mockEmail);
// Act
const processor = new OrderProcessor();
processor.processOrder('123');
// Assert
expect(mockEmail.sentEmails).toContainEqual({
to: '[email protected]',
type: 'confirmation'
});
});
});Requirements
- Node.js 14+
- TypeScript 4.5+
- Any test framework (Jest, Mocha, Vitest, etc.)
License
See LICENSE.md
