Sinon is unable to stub standalone functions such as the CreateCar
factory function in this scenario. Therefore, it is recommended to utilize Link Seams for this purpose. To achieve this, we will employ proxyquire to create our seams.
For example:
vehicle.ts
:
import { CarBuilder, CreateCar } from './builders/carBuilder';
export default class Vehicle {
private builder: CarBuilder;
constructor() {
this.builder = CreateCar();
}
createBmw(model) {
return this.builder.validate(model);
}
}
builders/carBuilder.ts
:
export interface CarBuilder {
validate(model): void;
}
export function CreateCar(): CarBuilder {
return { validate(model) {} };
}
vehicle.test.ts
:
import proxyquire from 'proxyquire';
import sinon from 'sinon';
describe('68197110', () => {
it('should pass', () => {
const carStub = { validate: sinon.stub() };
const CreateCarStub = sinon.stub().returns(carStub);
const Vehicle = proxyquire('./vehicle', {
'./builders/carBuilder': {
CreateCar: CreateCarStub,
},
}).default;
const sut = new Vehicle();
sut.createBmw('5 series');
sinon.assert.calledWithExactly(carStub.validate, '5 series');
});
});
Unit test results:
68197110
✓ should pass (1481ms)
1 passing (1s)
-------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------------|---------|----------|---------|---------|-------------------
All files | 83.33 | 100 | 50 | 83.33 |
68197110 | 100 | 100 | 100 | 100 |
vehicle.ts | 100 | 100 | 100 | 100 |
68197110/builders | 50 | 100 | 0| 50 |
carBuilder.ts | 50 | 100 | 0| 50 | 6
-------------------|---------|----------|---------|---------|-------------------