Search code examples
unit-testingtypescriptsinon

How do I use Sinon with Typescript?


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?


Solution

  • You may need to use an <any> type assertion to make the type wide before you narrow it to your specific type:

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

    Just to clarify one behaviour of sinon - although you pass in MyStuff.MyService, whatever you pass to the mock method is only used to provide better error messages.

    If you want the mock to have methods and properties, you need to add them.

    If you want automatically created fakes, you can grab the FakeFactory from tsUnit, which creates a fake version with some default values that you can opt to override - in JavaScript this is pretty easy stuff (plus by not using too much mock functionality, you can ensure you are testing behaviour rather than implementation).

    Example use of FakeFactory:

    var target = tsUnit.FakeFactory.getFake<RealClass>(RealClass);
    var result = target.run();
    this.areIdentical(undefined, result);