How do I use Sinon with Typescript?

Brandon picture Brandon · Jan 26, 2015 · Viewed 33.1k times · Source

If I use sinon with typescript then how do I cast the sinon mock to an instance of my object?

For instance a SinonMock would be returned but my controller under test may require a specific service passed in to its constructor.

var myServiceMock: MyStuff.MyService = <MyStuff.MyService (sinon.mock(MyStuff.MyService));

controllerUnderTest = new MyStuff.MyController(myServiceMock, $log);

Can sinon be used with Typescript?

Answer

Jan Molak picture Jan Molak · Jul 1, 2016

Sinon can create a stub based on a constructor quite easily if, instead of mock, you use the createStubInstance method.

An example using mocha, chai, sinon and sinon-chai, could look like this:

import * as sinon from 'sinon';
import * as chai from 'chai';

// ... imports for the classes under test

const expect    = chai.expect;
const sinonChai = require("sinon-chai");

chai.use(sinonChai);

describe('MyController', () => {
    it('uses MyService', () => {

        let myService  = sinon.createStubInstance(MyStuff.MyService),
            controller = new MyStuff.MyController(myService as any, ...);

        // ... perform an action on the controller 
        // that calls myService.aMethodWeAreInterestedIn

        // verify if the method you're interested in has been called if you want to
        expect(myService.aMethodWeAreInterestedIn).to.have.been.called;
    });
});

I've published an article, which you might find useful if you'd like to learn more about the different test doubles and how to use them with Sinon.js.

Hope this helps!

Jan