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);
});
});
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 {}
});
});
Related
I am writing a library which has an entry file that looks like this:
function MyLibrary(options){
this._options = {// defaults here};
this.setupOptions(options);
this._initInstance();
}
MyLibrary.prototype.randomMethod = function(){
}
MyLibrary.prototype._initInstance = function(){
this._loadImage();
this._internalInstance = new OtherThirdPartyDependency(this._options);
}
module.exports = MyLibrary;
In my tests, I would like to create a real instance of MyLibrary, but I want to create a stub of OtherThirdPartyDependency.
Here is my test file so far. How can I achieve this?
describe('My Library Module', () => {
let sandbox;
let myLibInstance;
beforeEach(() => {
sandbox = sinon.createSandbox({});
myLibInstance = new MyLibrary({option: 1, option: 2});
// FAILS HERE because initializing MyLibrary make a call OtherThirdPartyDependency constructor.
});
afterEach(() => {
sandbox.restore();
});
it('should call setOptions and _loadImage on init', () => {
expect(myLibInstance.setOptions).to.have.been.calledOnce;
expect(myLibInstance._loadImage).to.have.been.calledOnce;
})
});
There is a method in sinon createStubInstance, but I'm not sure how to apply in here because OtherThirdPartyDependency is not a method that I can directly stub on MyLibrary. How can I stub OtherThirdPartyDependency?
Apologies if this was asked before. Here is the module that I'd like to unittest inside file getStuff.js. I'm having difficulty stubbing theresolveThing module used here.
getStuff.js
const resolveThing = require('./resolveThing.js');
module.exports = async function getStuff(target, stuff) {
const { element, test, other } = resolveThing(target);
try {
return element;
} catch (error) {
throw new Error('Did not work.');
}
};
And here is my attempt at the unittest with stubbing using sinon. However when I try to run this it errors out with TypeError: Cannot stub non-existent own property resolveType. Anyone know how I can get this test to work?
const getStuff = require('../com/getStuff');
const resolveThing = require('../com/resolveThing');
const mochaccino = require('mochaccino');
const { expect } = mochaccino;
const sinon = require('sinon');
describe('com.resolveThing', function() {
beforeEach(function () {
sinon.stub(resolveThing, 'resolveThing').returns({element:'a',test:'b',other:'c'});
});
afterEach(function () {
resolveThing.restore();
});
it('Standard message', function() {
const answer = getAttribute('a','b');
expect(answer).toEqual('a');
});
});
sinon.stub(resolveThing, 'resolveThing').returns({element:'a',test:'b',other:'c'});
resolveThing must be an object and 'resolveThing' must be a function in the object, an exception is thrown if the property is not already a function.
I think this is what's hapning in your case.
I have 2 files controller.js and entity.js which interact with each other. I am testing controller.js, and it creates an instance of entity.js (class) and use one of its functions. How can I stub/mock/spy the call and the return of that method?
controller.js
const controller= async (req, res) => {
try {
...
const entity = new Entity({
...
});
const validation = await entity.validate();
...
return res.send()
}
} catch (error) {
return res.send(error)
}
};
Entity.js
class Entity{
constructor() {
...
}
...
async validate() {
...
return response;
}
}
Any idea how to test controller.js using supertest, sinon and chai?
Sinon will happily stub the function. Since it's a class method you just need to be sure to stub the function on the prototype:
const controller = async (req, res) => {
const entity = new Entity();
const validation = await entity.validate();
console.log(validation)
};
class Entity{
constructor() {}
async validate() {
return "real function";
}
}
// stub it
let stub = sinon.stub(Entity.prototype, 'validate')
stub.returns('stubbed function')
controller()
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.1.1/sinon.min.js"></script>
This solution uses Ava (but you should be able to adapt to Mocha easily). However I'm more familiar with testdouble. If you have no success with sinon (I'm sure you will), here's an alternative that you may want to consider.
So if we have burrito.js:
module.exports = class {
eat() {
return '🌯';
}
};
And lunch.js:
var Burrito = require('./burrito');
module.exports = () => (new Burrito()).eat();
Then in your test:
const td = require('testdouble');
const test = require('ava');
test('swap burrito', t => {
td.replace('./burrito', class FakeBurrito {
eat() {
return '🌮';
}
});
const lunch = require('./lunch');
t.is(lunch(), '🌮'); // PASS
t.is(lunch(), '🌯'); // FAIL
});
The key is to require your dependency (a burrito) before your subject under test (your lunch) requires it, so that you have time to fake it.
I have an issue with a unit test of a function which calls a class. It seems that it always calls the "official" class instance and not my mocked class. I'm not able to force my function to use my mocked instance...
There is a file with the function I want to test:
const myClass = require('./myClass');
const instance = new myClass();
module.exports.functionToTest = async function () {
// Some stuff...
const value = await instance.myMethod();
// Some stuff that define a result variable (partially with value).
return result;
}
There is a file with my class definition:
module.exports = class myClass {
async myMethod() {
const result = await someStuffWillResolveMaybeTrueOrFalse();
console.log('We used the original myMethod... Mocking has failed.');
return result;
}
}
There is a spec file:
const myFile = require('./myFile');
const myClass = require('./myClass');
describe('My test', async () => {
it('should mock myClass.myMethod in order to return false', () => {
const instance = new myClass();
instance.myMethod = jest.fn().mockResolvedValue(false);
const result = await myFile.functionToTest();
expect(result).toBeTruthy();
}
}
Unfortunately my test is passing (because myMethod return "true") and log "We used the original myMethod... Mocking has failed."
So I want to make my test always fail by mocking that myMethod to return false.
Can you help me? Thanks for your time.
Hm. I've found a solution.
See. A change in my file with the target function.
const myClass = require('./myClass');
// const instance = new myClass(); <== Not here...
module.exports.functionToTest = async function () {
const instance = new myClass(); // <== ...but there.
// Some stuff...
const value = await instance.myMethod();
// Some stuff that define a result variable (partially with value).
return result;
}
And my spec file :
const myFile = require('./myFile');
// I specify to Jest that I'll mock a file
jest.mock('./myClass');
const myClass = require('./myClass');
// I prepare the mock function. In that case a promise wich resolve 'false'
const mMock = jest.fn().mockResolvedValue(false);
// I mock the method 'myMethod' in 'myClass'
myClass.mockImplementation(() => {
return {
myMethod: mMock
};
});
// Then, I just take the test
describe('My test', async () => {
it('should mock myClass.myMethod in order to return false', () => {
const result = await myFile.functionToTest();
expect(result).toBeFalsy();
}
}
I'm trying to use sinon stub to replace a function that might take along time. But when I run the tests, the test code doesn't seem to be using the sinon stubs.
Here is the code I'm trying to test.
function takeTooLong() {
return returnSomething();
}
function returnSomething() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('ok')
}, 1500)
})
}
module.exports = {
takeTooLong,
returnSomething
}
and this is the test code.
const chai = require('chai')
chai.use(require('chai-string'))
chai.use(require('chai-as-promised'))
const expect = chai.expect
chai.should()
const db = require('./database')
const sinon = require('sinon')
require('sinon-as-promised')
describe('Mock the DB connection', function () {
it('should use stubs for db connection for takeTooLong', function (done) {
const stubbed = sinon.stub(db, 'returnSomething').returns(new Promise((res) => res('kk')));
const result = db.takeTooLong()
result.then((res) => {
expect(res).to.equal('kk')
sinon.assert.calledOnce(stubbed);
stubbed.restore()
done()
}).catch((err) => done(err))
})
I get an assertion error
AssertionError: expected 'ok' to equal 'kk'
+ expected - actual
-ok
+kk
What am I doing wrong? Why isn't the stub being used ? The test framework in Mocha.
Sinon stubs the property of the object, not the function itself.
In your case you are exporting that function within an object.
module.exports = {
takeTooLong,
returnSomething
}
So in order to properly call the function from the object, you need to replace your function call with the reference to the export object like :
function takeTooLong() {
return module.exports.returnSomething();
}
Of course based on your code, you can always refactor it :
var exports = module.exports = {
takeTooLong: function() { return exports.returnSomething() }
returnSomething: function() { /* .. */ }
}
You might want to have a look at Proxyquire to stub/spy directly exported functions.
https://www.npmjs.com/package/proxyquire/