Sinon extension providing functions to:
- stub all object methods
- stub interface
- You have a version of Node.js >= v8.4.0
- You have installed Typescript
npm install ts-sinon
Importing stubObject function:
- import single function:
import { stubObject } from "ts-sinon";
- import as part of sinon singleton:
import * as sinon from "ts-sinon";
const stubObject = sinon.stubObject;
Stub all object methods:
class Test {
method() { return 'original' }
}
const test = new Test();
const testStub = stubObject<Test>(test);
testStub.method.returns('stubbed');
expect(testStub.method()).to.equal('stubbed');
Partial stub:
class Test {
methodA() { return 'A: original' }
methodB() { return 'B: original' }
}
const test = new Test();
const testStub = stubObject<Test>(test, ['methodA']);
expect(testStub.methodA()).to.be.undefined;
expect(testStub.methodB()).to.equal('B: original');
Stub with predefined return values:
class Test {
method() { return 'original' }
}
const test = new Test();
const testStub = stubObject<Test>(test, { method: 'stubbed' });
expect(testStub.method()).to.equal('stubbed');
Importing stubInterface function:
- import single function:
import { stubInterface } from "ts-sinon";
- import as part of sinon singleton:
import * as sinon from "ts-sinon";
const stubInterface = sinon.stubInterface;
Interface stub with predefined return values (recommended):
interface Test {
method(): string;
}
const testStub = stubInterface<Test>({ method: 'stubbed' });
expect(testStub.method()).to.equal('stubbed');
Interface stub (not recommended due to interface stub method return types incompatibility - if the return value of stubInterface method is not cast to "any" type and returned type of interface method is not compatible with "object" we'll get a compiler error).
interface Test {
method(): string;
}
// if we have "Test" type instead of "any" code does not compile
const testStub: any = stubInterface<Test>();
expect(testStub.method()).to.be.undefined;
testStub.method.returns('stubbed');
expect(testStub.method()).to.equal('stubbed');
By importing 'ts-sinon' you have access to all sinon methods.
import * as sinon from "ts-sinon";
const functionStub = sinon.stub();
const spy = sinon.spy();
// etc.
npm test