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?
In Typescript this can be achieved by using sinon. createStubInstance and SinonStubbedInstance class.
We can use Jest to create mocks in our test - objects that replace real objects in our code while it's being tested. In our previous series on unit testing techniques using Sinon. js, we covered how we can use Sinon. js to stub, spy, and mock Node.
Sinon JS is a popular JavaScript library that lets you replace complicated parts of your code that are hard to test for “placeholders,” so you can keep your unit tests fast and deterministic, as they should be.
Mocks allow you to create a fake function that passes or fails depending on your needs. You can ensure it was called with certain arguments, or check how many times it was called. You must call mock() on an object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With