I have some dependency in the tested module.
sendResponse.js:
module.exports = function sendResponse(res, data) {
res.send(data);
};
testedModule.js:
const login = require('.../sendResponse');
exports.postLogin = withServerErrorHandler(async (req, res) => {
const { body } = req;
const { email, password } = body;
const user = await login(email, password);
return sendResponse(res, user);
});
And I want to mock sendResponse module and count its calls.
const testedModule = require('.../testedModule');
jest.mock('.../sendResponse', () => jest.fn());
const sendResponse = require('.../sendResponse');
describe('testedModule', () => {
const res = {
//..
};
const req = {
//..
};
describe('Authentication', () => {
test('should pass', async (done) => {
await testedModule.postLogin(req, res);
expect(sendResponse).toHaveBeenCalledTimes(1);
done();
});
})
});
Unfortunately, Jest always gives me that result, It looks like Jest jest spy on jest.fn() function, not specific ref. How can I deal with it?
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
Related
Problem
I have an Action which awaits an API function. The happy path in the try is easily testable with my mocked API. However, unsure as to the best way to test and cover the .catch.
Actions
import {getRoles} from '../shared/services/api';
export const Actions = {
SET_ROLES: 'SET_ROLES'
};
export const fetchRoles = () => async dispatch => {
try {
const response = await getRoles();
const roles = response.data;
dispatch({
type: Actions.SET_ROLES,
roles
});
} catch (error) {
dispatch({
type: Actions.SET_ROLES,
roles: []
});
}
};
Actions Test
import {fetchRoles} from '../party-actions';
import rolesJson from '../../shared/services/__mocks__/roles.json';
jest.mock('../../shared/services/api');
describe('Roles Actions', () => {
it('should set roles when getRoles() res returns', async () => {
const mockDispatch = jest.fn();
await fetchRoles()(mockDispatch);
try {
expect(mockDispatch).toHaveBeenCalledWith({
type: 'SET_ROLES',
roles: rolesJson
});
} catch (e) {
// console.log('fetchRoles error: ', e)
}
});
// Here is the problem test, how do we intentionally cause
// getRoles() inside of fetchRoles() to throw an error?
it('should return empty roles if error', async () => {
const mockDispatch = jest.fn();
await fetchRoles('throwError')(mockDispatch);
expect(mockDispatch).toHaveBeenCalledWith({
type: 'SET_ROLES',
roles: []
});
});
});
Mocked API
import rolesJson from './roles.json';
export const getRoles = async test => {
let mockGetRoles;
if (test === 'throwError') {
// console.log('sad')
mockGetRoles = () => {
return Promise.reject({
roles: []
});
};
} else {
// console.log('happy')
mockGetRoles = () => {
return Promise.resolve({
roles: rolesJson
});
};
}
try {
const roles = mockGetRoles();
// console.log('api mocks roles', roles);
return roles;
} catch (err) {
return 'the error';
}
};
^ Above you can see what I tried, which did work, but it required me to change my code in a way that fit the test, but not the actual logic of the app.
For instance, for this test to pass, I have to pass in a variable through the real code (see x):
export const fetchRoles = (x) => async dispatch => {
try {
const response = await getRoles(x);
const roles = response.data;
How can we force getRoles in our mock to throw an error in our sad path, .catch test?
You can mock getRoles API on per-test basis instead:
// getRoles will be just jest.fn() stub
import {getRoles} from '../../shared/services/api';
import rolesJson from '../../shared/services/__mocks__/roles.json';
// without __mocks__/api.js it will mock each exported function as jest.fn();
jest.mock('../../shared/services/api');
it('sets something if loaded successfully', async ()=> {
getRoles.mockReturnValue(Promise.resolve(rolesJson));
dispatch(fetchRoles());
await Promise.resolve(); // so mocked API Promise could resolve
expect(someSelector(store)).toEqual(...);
});
it('sets something else on error', async () => {
getRoles.mockReturnValue(Promise.reject(someErrorObject));
dispatch(fetchRoles());
await Promise.resolve();
expect(someSelector(store)).toEqual(someErrornessState);
})
I also propose you concentrate on store state after a call not a list of actions dispatched. Why? Because actually we don't care what actions in what order has been dispatched while we get store with data expected, right?
But sure, you still could assert against dispatch calls. The main point: don't mock result returned in __mocks__ automocks but do that on peer-basis.
I resolved the test and got the line coverage for the .catch by adding a function called mockGetRolesError in the mock api file:
Thanks to #skyboyer for the idea to have a method on the mocked file.
import {getRoles} from '../shared/services/api';
export const Actions = {
SET_ROLES: 'SET_ROLES'
};
export const fetchRoles = () => async dispatch => {
try {
const response = await getRoles();
const roles = response.data;
// console.log('ACTION roles:', roles);
dispatch({
type: Actions.SET_ROLES,
roles
});
} catch (error) {
dispatch({
type: Actions.SET_ROLES,
roles: []
});
}
};
Now in the test for the sad path, I just have to call mockGetRolesError to set the internal state of the mocked api to be in a return error mode.
import {fetchRoles} from '../party-actions';
import rolesJson from '../../shared/services/__mocks__/roles.json';
import {mockGetRolesError} from '../../shared/services/api';
jest.mock('../../shared/services/api');
describe('Roles Actions', () => {
it('should set roles when getRoles() res returns', async () => {
const mockDispatch = jest.fn();
try {
await fetchRoles()(mockDispatch);
expect(mockDispatch).toHaveBeenCalledWith({
type: 'SET_ROLES',
roles: rolesJson
});
} catch (e) {
return e;
}
});
it('should return empty roles if error', async () => {
const mockDispatch = jest.fn();
mockGetRolesError();
await fetchRoles()(mockDispatch);
expect(mockDispatch).toHaveBeenCalledWith({
type: 'SET_ROLES',
roles: []
});
});
});
I'm currently making a small server in JavaScript and as part of the learning process I'm writing unit tests for the functions. Unfortunately I ran into major difficulties with a certain test that handles a promise. Below is the router module, with a separate handlePUT function for ease of testing.
const express = require('express');
const service = require('../service/user.service');
const dutyStatusRouter = express.Router();
const output = console;
function handlePUT(req, res) {
service.updateUserStatus()
.then((fulfilled) => {
res.status(fulfilled);
res.send();
})
.catch(() => {
res.status(500);
res.send();
});
}
dutyStatusRouter.route('/').put(handlePUT);
The updateUserStatus function basically toggles a Boolean in a database and looks somewhat like this:
function updateUserStatus() {
return new Promise((resolve, reject) => {
if (…) {
resolve(201);
} else if (…) {
resolve(200);
} else {
reject();
}
});
}
As for the unit tests, I'm using mocha/chai, with proxyquire to create a mock updateUserStatus.
const chai = require('chai');
const sinon = require('sinon');
const proxyquire = require('proxyquire');
const serviceStub = {};
describe('=== Unit test ===', () => {
it('Handle PUT test: promise kept', async () => {
const dutyStatusRouter = proxyquire('../../router/duty-status.router', {
'../service/user.service': serviceStub,
});
serviceStub.updateUserStatus = () => {
return new Promise((resolve, reject) => {
resolve(200);
});
};
const res = {
status: sinon.fake(),
send: sinon.fake(),
};
await dutyStatusRouter.handlePUT({}, res);
chai.assert(res.status.calledOnceWith(200));
});
});
Whenever I try to run the unit test, I get the error Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.. If I try to add done() it still fails by giving the error message Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
Found a solution that works, so I'm adding it here:
const chai = require('chai');
const sinon = require('sinon');
const proxyquire = require('proxyquire');
const serviceStub = {};
const dutyStatusRouter = proxyquire('../../router/duty-status.router', {
'../service/user.service': serviceStub,
});
describe('=== Unit test ===', () => {
it('Handle PUT test: promise kept', (done) => {
serviceStub.updateUserStatus = sinon.stub().resolves(200);
const res = {
status: sinon.fake(),
send: sinon.fake(),
};
dutyStatusRouter.handlePUT({}, res).then(() => {
chai.assert(res.status.calledWith(200));
done();
});
});
});
Note: I changed the handlePUT function just a bit, it now looks like this (I just added a return):
function handlePUT(req, res) {
return service.updateUserStatus()
.then((fulfilled) => {
output.log('Promise fulfilled');
res.status(fulfilled);
res.send();
})
.catch(() => {
output.log('Promise unfulfilled');
res.status(500);
res.send();
});
}
I am trying to unit test a JavaScript promise, that contains a firebase query, using mocha, chai, sinon. I am trying to mock the database using sinon rather than actually making a request to the database. However, I am unable to implement it correctly.
Here is my promise in the file '/services/pr_services:
exports.getUserInfo = (userId) => {
return new Promise((resolve, reject) => {
const userProfile = {};
const userProfileRef = database.ref('profiles').child(userId);
userProfileRef.once('value', (snap) => {
if (snap.exists()) {
const userProfileData = snap.val();
resolve(userProfile);
} else {
reject();
}
});
});
};
The variable database contains the database configuration like credentials, database url, etc
Here is my code for the test case:
const chai = require('chai');
const sinon = require('sinon');
const admin = require('firebase-admin');
const database = require('../database');
const services = require('../services/pr_services');
const should = chai.should();
describe('Database functions', () => {
let adminInitStub;
before(() => {
adminInitStub = sinon.stub(admin, 'initializeApp');
});
describe('get profile info', () => {
it('should return a non empty object', (done) => {
beforeEach(() => {
services.getUserInfo = sinon.stub();
});
afterEach(() => {
services.getUserInfo.reset();
});
const userId = 'jim123';
const snap = {
name: 'Jim Dani',
address: 'Porto'
};
const userProfileRef = database.ref('profiles').child(userId);
userProfileRef.once('value').returns(Promise.resolve(snap));
services.getUserInfo
.then(info => {
info.should.be.a('object');
info.should.equal(snap);
done();
})
.catch(err => {
should.not.exist(err);
done();
});
});
});
after(() => {
adminInitStub.restore();
test.cleanup();
});
});
Can anyone point out where I am going wrong and kindly point me in right direction.
Thanks.
I write a test with jest to test one of my middleware.
const asyncAll = (req, res, next) => {
const queue = [
service.exchangeLongTimeToken(req),
service.retrieveUserInfo(req),
];
Promise.all(queue).then((values) => {
res.locals.auth = values[0];
res.locals.user = values[1];
next();
}).catch((err) => {
next(err)
});
};
The test file is like this:
const httpMocks = require('node-mocks-http');
const testData = require('../../testdata/data.json');
describe('Test asyncAll', () => {
let spy1 = {};
let spy2 = {};
const mockNext = jest.fn();
afterEach(() => {
mockNext.mockReset();
spy1.mockRestore();
spy2.mockRestore();
});
test('Should call next() with no error when no error with 2 requests', () => {
spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
return Promise.resolve(testData.fbLongTimeToken);
});
spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
return Promise.resolve(testData.fbUserInfo);
});
const request = httpMocks.createRequest();
const response = httpMocks.createResponse();
asyncAll(request, response, mockNext);
expect(spy1).toBeCalled();
expect(spy2).toBeCalled();
expect(mockNext).toBeCalled();
expect(mockNext).toBeCalledWith();
expect(mockNext.mock.calls.length).toBe(1);
});
}
The error is like this:
Error: expect(jest.fn()).toBeCalled()
Expected mock function to have been called.
at Object.<anonymous> (tests/backend/unit/fblogin/asyncAll.test.js:39:26)
Which reflects the line:
expect(mockNext).toBeCalled();
Why it doesn't get called?
I read the documents about jest, it says I need to return the promise in order to test the value. But the asyncAll() doesn't return a promise, instead, it consumes a promise, how to deal with this?
You have to notify Jest about the promises you create in the test, have a look at the docs on this topic:
test('Should call next() with no error when no error with 2 requests', async() => {
const p1 = Promise.resolve(testData.fbLongTimeToken);
const p2 = Promise.resolve(testData.fbUserInfo);
spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
return p1
});
spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
return p2
});
const request = httpMocks.createRequest();
const response = httpMocks.createResponse();
asyncAll(request, response, mockNext);
await Promise.all([p1,p2])
expect(spy1).toBeCalled();
expect(spy2).toBeCalled();
expect(mockNext).toBeCalled();
expect(mockNext).toBeCalledWith();
expect(mockNext.mock.calls.length).toBe(1);
});
I want to write some unit-tests for my applicatin, can I somehow "mock" some dependencies used with require('dependencyname')?
You are looking for Proxyquire :)
//file1
var get = require('simple-get');
var assert = require('assert');
module.exports = function fetch (callback) {
get('https://api/users', callback);
};
//test file
var proxyquire = require('proxyquire');
var fakeResponse = {status:200};
var fetch = proxyquire('./get', {
'simple-get': function (url, callback) {
process.nextTick(function () {
callback(null, fakeResponse)
})
}
});
fetch(function (err, res) {
assert(res.statusCode, 200)
});
Straight out of their docs.
yes, for example with jest => https://facebook.github.io/jest/
// require model to be mocked
const Mail = require('models/mail');
describe('test ', () => {
// mock send function
Mail.send = jest.fn(() => Promise.resolve());
// clear mock after each test
afterEach(() => Mail.send.mockClear());
// unmock function
afterAll(() => jest.unmock(Mail.send));
it('', () =>
somefunction().then(() => {
// catch params passed to Mail.send triggered by somefunction()
const param = Mail.send.mock.calls[0][0];
})
);
});