A modern framework for creating substitutes from interfaces during TypeScript development based on the NSubstitute philosophy
npm install @testpossessed/ts-substitutejavascript
export interface IService {
doIt(arg1: string, arg2: number): string;
}
export class ServiceConsumer : {
constructor(private myService: IService) {}
callDoIt(arg1: string, arg2: string) {
const result = this.myService.doIt(arg1, arg2);
/// do something with result
}
}
`
Then when testing ServiceConsumer you can use ts-substitute to create a substitute for IService that can be tested for interactions and configured to return output specific to the test case. That is it, simple but powerful. Read on to learn more.
$3
ts-substitute is published as an NPM package under the @testpossessed namespace
`bash
npm install -D @testpossessed/ts-substitute
`
$3
ts-substitute exports two static objects Substitute and Arg these need to be imported into a test module to be used. Substitute is required. Arg is used for argument matching when asserting interactions between consumer and substitute so can be considered optional, but you will use it pretty often so the following is the most likely import statement you will use.
`javascript
import { Substitute, Arg } from 'ts-substitute';
`
With the imports taken care of you can write tests like this (jasmine syntax)
`javascript
describe('ServiceConsumer', () => {
let sub: SubstituteOf;
let service: ServiceConsumer;
beforeEach(() => {
sub = Substitute.for();
service = new ServiceConsumer(sub);
});
it('should use service', () => {
sub.doIt(Arg.any(), Arg.any()).returns('return this');
service.callDoIt('one', 'two');
expect(sub.recieved().doIt('one', 'two'));
});
});
`
#WIP
This readme is very much a work in progress and should be completed at some point. However the library was developed applying TDD so the tests should provide plenty of usage examples in the meantime. Also TypeDoc has been setup to generate API documentation from comments. The latest API documentation can be generated and viewed with using lite-server.
`bash
npm start
`
Or you can run
`bash
npm run docgen
``