How to mock a function in jasmine - unit-testing

I am trying to unit test the following code using jasmine but I can't seem to mock the checkStatus function. What am I seem to get wrong? It seems like when i actually call the Booking.saveBooking method it is not using the mocked version of the checkStatus. Please help.
Booking.js
const checkStatus = (id) => {
.. // some code here
return new Promise((resolve, reject)=>{
resolve(value);
});
}
const saveBooking =(req) => {
checkStatus(req.id).then(()=>{
//save booking here ..
}).catch((error)=>{
throw new Error();
});
}
module.exports ={saveBooking, checkStatus}
booking.Spec.js
const Booking = require('Booking');
describe('Booking',()=>{
const req = {
id: 2133,
customer_name: 'John Smith',
contact_number: '888-8888',
contact_email: 'cam888#example.com'
};
it('Should check the status', async ()=>{
spyOn(Booking, "checkStatus").and.callFake(function() {
var deferred = $q.defer();
deferred.resolve(true);
return deferred.promise;
});
await Booking.saveBooking(req);
expect(Booking.checkStatus).toHaveBeenCalled()
});
});
I am getting an error Error: Expected spy checkStatus to have been called.
It seems like saveBooking method it is not using the mocked version of the checkStatus.

Related

Im trying to mock a function from a service but Jest keeps calling the actual function instead of the mock function

I'm using Jest to test a function from a service that uses axios to make some api calls. The problem is that Jest keeps calling the actual services function instead of the mocked service function. Here is all of the code:
The tests:
// __tests__/NotificationService.spec.js
const mockService = require('../NotificationService').default;
beforeEach(() => {
jest.mock('../NotificationService');
});
describe('NotificationService.js', () => {
it('returns the bell property', async () => {
expect.assertions(1);
const data = await mockService.fetchNotifications();
console.log(data);
expect(data).toHaveProperty('data.bell');
});
});
The mock:
// __mocks__/NotificationService.js
const notifData = {
bell: false,
rollups: [
{
id: 'hidden',
modifiedAt: 123,
read: true,
type: 'PLAYLIST_SUBSCRIBED',
visited: false,
muted: false,
count: 3,
user: {
id: 'hidden',
name: 'hidden'
},
reference: {
id: 'hidden',
title: 'hidden',
url: ''
}
}
],
system: [],
total: 1
};
export default function fetchNotifications(isResolved) {
return new Promise((resolve, reject) => {
process.nextTick(() =>
isResolved ? resolve(notifData) : reject({ error: 'It threw an error' })
);
});
}
The service:
import axios from 'axios';
// hardcoded user guid
export const userId = 'hidden';
// axios instance with hardcoded url and auth header
export const instance = axios.create({
baseURL: 'hidden',
headers: {
Authorization:
'JWT ey'
}
});
/**
* Notification Service
* Call these methods from the Notification Vuex Module
*/
export default class NotificationService {
/**
* #GET Gets a list of Notifications for a User
* #returns {AxiosPromise<any>}
* #param query
*/
static async fetchNotifications(query) {
try {
const res = await instance.get(`/rollups/user/${userId}`, {
query: query
});
return res;
} catch (error) {
console.error(error);
}
}
}
I've tried a couple of variations of using require instead of importing the NotificationService, but it gave some other cryptic errors...
I feel like I'm missing something simple.
Help me please :)
The problem is that Jest keeps calling the actual services function instead of the mocked service function.
babel-jest hoists jest.mock calls so that they run before everything else (even import calls), but the hoisting is local to the code block as described in issue 2582.
I feel like I'm missing something simple.
Move your jest.mock call outside the beforeEach and it will be hoisted to the top of your entire test so your mock is returned by require:
const mockService = require('../NotificationService').default; // mockService is your mock...
jest.mock('../NotificationService'); // ...because this runs first
describe('NotificationService.js', () => {
it('returns the bell property', async () => {
...
});
});

How to test async function with axios?

I need to test async function using mocha.
Tried to test function that returns Promise from axios. Looked through many examples with axios-mock-adapter to solve my issue. BUT: axios sends REAL request, not mock as expected.
describe ('login sendRequest', () => {
let sandbox = null;
before(() => {
sandbox = sinon.createSandbox();
});
after(() => {
sandbox.restore();
});
it('should create and return REST promise', done => {
const mockAdapter = new MockAdapter(axios);
const data = { response: true };
mockAdapter.onAny('http://google.com').reply(200, data);
const requestParams = {
method: 'post',
url: 'http://google.com',
data: {},
adapter: adapter,
};
logic.sendRequest(requestParams).then(response => {
console.log(response);
done();
}).catch(err => {
console.log(err);
});
});
});
logic.js
export async function sendRequest(requsetParams) {
return await requestSender.request(requsetParams);
}
Expected to get 200 response and mock data that was set before. Why I don't get the response I need? May someone help?

How to mock pg-promise library with jest

I am trying to mock the pg promise library. I want to be able mock return whether the promise rejects or resolves. Here is an example function and test:
const pgp = require('pg-promise')({});
const someFunc = callback => {
const db = pgp('connectionString');
db
.none('create database test;')
.then(() => {
callback(null, 'success');
})
.catch(err => {
callback(err);
});
};
module.exports = {
someFunc
};
And i wanna test it like so:
const { someFunc } = require('./temp');
let pgp = require('pg-promise')({
noLocking: true
});
// HOW TO MOCK?
describe('test', () => {
beforeEach(() => {
jest.resetModules();
jest.resetAllMocks();
});
it('should test', () => {
let db = pgp('connectionString');
// how to mock this?
db.none = jest.fn();
db.none.mockReturnValue(Promise.reject('mock'));
const callback = jest.fn();
someFunc(callback);
return new Promise(resolve => setImmediate(resolve)).then(() => {
expect(callback.mock.calls.length).toEqual(1);
});
});
});
You can mock the pgp object with a dumb mock like so:
const { someFunc } = require('./temp');
let pgp = jest.fn(() => ({
none: jest.fn(),
})
jest.mock('pg-promise') // Jest will hoist this line to the top of the file
// and prevent you from accidentially calling the
// real package.
describe('test', () => {
beforeEach(() => {
jest.resetModules();
jest.resetAllMocks();
});
it('should test', () => {
let db = pgp('connectionString');
db.none.mockRejectedValue('mock'); // This is the mock
const callback = jest.fn();
someFunc(callback);
return new Promise(resolve => setImmediate(resolve)).then(() => {
expect(callback.mock.calls.length).toEqual(1);
});
});
});
Its an old question, but here is a new answer:
You can have a look at pg-mem, a library I released recently which emulates an in-memory postgres instance.
It supports most of the usual SQL queries (but will fail on less frequent syntaxes - file an issue if you encounter such a situation).
I wrote an article about it here
For your use case, see the this section

Unit testing bluebird promise bind function

I have the following function that uses bind to bind a context to the then chains. When i try and test it, it throws
TypeError: redisClient.hgetallAsync(...).bind is not a function
myFunc() {
let self = this;
return redisClient.hgetallAsync('abcde')
.bind({ api: self })
.then(doStuff)
.catch(err => {
// error
});
}
Test
let redisClient = { hgetallAsync: sinon.stub() };
describe('myFunc', () => {
beforeEach(() => {
redisCLient.hgetallAsync.resolves('content!');
});
it('should do stuff', () => {
return myFunc()
.should.eventually.be.rejectedWith('Internal Server Error')
.and.be.an.instanceOf(Error)
.and.have.property('statusCode', 500);
});
});
The hgetallAsync stub is returning a plain JS Promise rather than a Bluebird promise.
To use a Bluebird promise, you need to tell Sinon to do so using .usingPromise().
let redisClient = { hgetallAsync: sinon.stub().usingPromise(bluebird.Promise) };
Documentation Link:
http://sinonjs.org/releases/v4.1.2/stubs/#stubusingpromisepromiselibrary

sinon stub a method that was executed in then call of promise

describe("/test" , ()=> {
// separate class 2
class2 = {
// function that i wanna stub
hi: function () {
return "hi";
}
}
// separate class 1
class1 = {
// function that i have stubbed and tested
method1: function() {
return new Promise((resolve, reject) => {
resolve(num);
})
}
}
// method that i will execute
var parent= function (){
class1.method1().then(()=>{
class2.hi();
})
}
// the test
it("should stub hi method",()=>{
var hiTest = sinon.stub(class2, 'hi').resolves(5);
var method1Test = sinon.stub(class1 , 'method1').resolves(5);
// this start the execution of the promise with then call
parent();
// this works fine and test pass
expect(method1Test.calledOnce.should.be.true);
// this doesn't work although i executed the function
expect(hiTest.calledOnce.should.be.true);
})
})
what i wanna do is test the hi method correctly .. because when i test if the method is executed once or not
although i executed it in the then call of the promise it doesn't show that and it make the calledOnce test fail
The problem here is that you are testing the code as if it is synchronous, when it is not (as you are using Promise).
To be able to test this properly we need to be able to hook onto the promise chain that is started with parentcalling class1.method1.
We can do this by returning the promise that calling class1.method1 returns.
In terms of the test itself, we need to make sure Mocha doesnt end the test while we are waiting for the promises, so we use the done callback parameter to tell Mocha when we think the test is finished.
describe("/test", ()=> {
class2 = {
hi: function () {
return "hi";
}
}
class1 = {
method1: function() {
return new Promise((resolve, reject) => {
resolve(num);
})
}
}
var parent = function (){
return class1.method1().then(()=>{
class2.hi();
})
}
it("should stub hi method", (done)=> {
var hiTest = sinon.stub(class2, 'hi').returns(5);
var method1Test = sinon.stub(class1 , 'method1').resolves(5);
parent().then(() => {
expect(method1Test.calledOnce.should.be.true);
expect(hiTest.calledOnce.should.be.true);
done();
});
})
})