Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
Brandon Avatar asked Jan 26 '15 18:01

Brandon


People also ask

Does Sinon work with typescript?

In Typescript this can be achieved by using sinon. createStubInstance and SinonStubbedInstance class.

Can I use Sinon with jest?

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.

What is Sinon used for?

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.

How do you mock a function in Sinon?

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.


1 Answers

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

like image 124
Jan Molak Avatar answered Sep 21 '22 04:09

Jan Molak