I'd like to unit test the following ES6 class:
// service.js const InternalService = require('internal-service'); class Service { constructor(args) { this.internalService = new InternalService(args); } getData(args) { let events = this.internalService.getEvents(args); let data = getDataFromEvents(events); return data; } } function getDataFromEvents(events) {...} module.exports = Service;
How do I mock constructor with Sinon.JS in order to mock getEvents
of internalService
to test getData
?
I looked at Javascript: Mocking Constructor using Sinon but wasn't able to extract a solution.
// test.js const chai = require('chai'); const sinon = require('sinon'); const should = chai.should(); let Service = require('service'); describe('Service', function() { it('getData', function() { // throws: TypeError: Attempted to wrap undefined property Service as function sinon.stub(Service, 'Service').returns(0); }); });
In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). Since calls to jest. mock() are hoisted to the top of the file, Jest prevents access to out-of-scope variables.
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.
to stub the myMethod instance method in the YourClass class. We call callsFake with a callback that returns the value we want for the fake method. sinon. stub(YourClass, "myStaticMethod").
If you need to check that a certain value is set before a function is called, you can use the third parameter of stub to insert an assertion into the stub: var object = { }; var expectedValue = 'something'; var func = sinon. stub(example, 'func', function() { assert. equal(object.
You can either create a namespace or create a stub instance using sinon.createStubInstance
(this will not invoke the constructor).
Creating a namespace:
const namespace = { Service: require('./service') }; describe('Service', function() { it('getData', function() { sinon.stub(namespace, 'Service').returns(0); console.log(new namespace.Service()); // Service {} }); });
Creating a stub instance:
let Service = require('./service'); describe('Service', function() { it('getData', function() { let stub = sinon.createStubInstance(Service); console.log(stub); // Service {} }); });
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