Mocking an ES6 class function with Jest - javascript

I have a question about how can I mock an ES6 class instance using Jest which is used by the method I actually want to test.
My real case is trying to test a Redux async action creator that make a request and dispatch some action depending on the request result.
This is a simplified example of the use case :
// communication.js
// An exported ES6 class module with proxy to the request library.
import post from './post';
export default class communication {
getData(data, success, error) {
const res = post(data);
if(res) {
success();
} else {
error();
}
}
}
// communicatorAssist.js
// A redux async function using communication.js
import communication from './communication';
// ...
export function retrieveData() {
return dispatch => {
const data = { name: 'michel'};
communication.getData(data,
(res) => dispatch(successAction(res)),
(res) => dispatch(errorAction(res));
}
}
// communicatorAssist.test.js testing the communicatorAssist
import { retrieveData } from 'communicatorAssist';
// communication.getData should call success callback
// for this test.
it('Should call the success callback', () => {
retrieveData();
// Assert that mocked redux store contains actions
});
// communication.getData should call error callback
// for this test.
it('Should call the error callback', () => {
retrieveData();
// Assert that mocked redux store contains actions
});
What I want is mocking the communication class in the test and change the behaviour of the getData() function in each test to call success and error callbacks without any call to post method.
I only success to mock the getData() function for the whole test file with this snippet at the top of it :
import communication from '../communication'
jest.mock('../communication', () => (() => ({
getData: (success, error) => success()
})));
but I can't switch between implementation in different test case.
I figure that something using .mockImplementation() could do the stuff but I can't make this work in my case (I saw examples using it for module exporting functions but not for classes ).
Does anyone have an idea ?
Edit :
I forgot a part in the code exemple : the communication class instance creation which I think is the "problem" for mocking it :
const com = new communication();
If com is instanciated at a global level in the communicatorAssist.js file : it fail with communication.getData is not a function error.
But if I set the instanciation inside the retrieveData() function, Andreas Köberle snippet work's fine :
import communication from '../communication'
jest.mock('../communication', () => jest.fn());
communication.mockImplementation(
() => ({
getData: (success, error) => success()
})
)
(jest.mock() factory parameter need to return a function not directly jest.fn)
I don't know why it's not working using a file global scope instance.

You need to mock the module with jest.fn() then you can import it and change the behaviour of it using mockImplementation:
import communication from '../communication'
jest.mock('../communication', jest.fn());
communication.mockImplementation(
() => ({
getData: (success, error) => success()
})
)

Related

Mocking a function returned by a react hook

I'm building a pagination using the useQuery hook as part of the Apollo Client in React, which exposes a function called fetchMore seen here: https://www.apollographql.com/docs/react/data/pagination/
Everything works fine, but I'm trying to write a test one of the use cases, which is when the fetchMore function fails due to a network error. The code in my component looks like this.
const App = () => {
// Some other component logic
const {loading, data, error, fetchMore} = useQuery(QUERY)
const handleChange = () => {
fetchMore({
variables: {
offset: data.feed.length
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) return prev;
return Object.assign({}, prev, {
feed: [...prev.feed, ...fetchMoreResult.feed]
});
}
}).catch((e) => {
// handle the error
})
}
}
Basically I want to test the case where the fetchMore function function throws an Error. I DON'T want to mock the entire useQuery though, just the fetchMore function. What would be the best way to mock just the fetchMore function in my test?
One way to do it is to just mock the hook
In your spec file:
import { useQuery } from '#apollo/react-hooks'
jest.mock('#apollo/react-hooks',() => ({
__esModule:true
useQuery:jest.fn()
});
console.log(useQuery) // mock function - do whatever you want!
/*
e.g. useQuery.mockImplementation(() => ({
data:...
loading:...
fetchMore:jest.fn(() => throw new Error('bad'))
});
*/
You could also mock the stuff that goes on "behind the scenes" to simulate a network error, do whatever you need to to test your catch.
EDIT:
Search for __esModule: true on this page and you'll understand.
It's probably easier to just mock the whole function and return everything as mock data. But you can unmock it to use the real one so as not to conflict with other tests.

How to mock implementation of a function called by a service being tested?

I have a NestJS project I'm working on, and I need to write unit tests of my services.
I have a service called BigQueryService that uses #google-cloud/bigquery to access a Big Query dataset and perform a query. I also have another service (lets call it MyService) whose job is to build the query that I need depending on some other logic, and pass it to the BigQueryService, receive the query result from it and return it to the controller, which will in turn send the data through an endpoint.
I need to write unit tests for MyService, and for that I need to mock the BigQueryService in a way that doesn't require it to resolve BigQueryService's dependencies. Here's some of my code:
bigquery.service.ts:
import { Injectable } from '#nestjs/common';
import { BigQuery } from '#google-cloud/bigquery';
...
#Injectable()
export class BigqueryService {
...
constructor(
...
) {
...
}
async executeQuery(querySentence: string): Promise<Array<any>> {
...
return response;
}
}
MyService.service.ts:
import { Injectable } from '#nestjs/common';
import { BigqueryService } from '../bigquery/bigquery.service';
//the following is just a service that helps log the results of this service
import { MyLogger } from '../../config-service/logger.service';
...
#Injectable()
export class MyService {
constructor(
private readonly bigqueryService: BigqueryService,
private readonly logger: MyLogger,
) { }
...
async myFunc(request: RequestInterface): Promise<Array<ResponseInterface>> {
let query = (some code to create a query i want)
return await this.bigqueryService.executeQuery(query);
}
For the tests, I followed the answers in this thread: Mock a method of a service called by the tested one when using Jest
jest.mock('../services/bigquery/bigquery.service', () => jest.fn())
const bq = require('../services/bigquery/bigquery.service')
jest.mock('../config-service/logger.service', () => jest.fn())
const ml = require('../config-service/logger.service')
const executeQuery = jest.fn()
executeQuery.mockReturnValue('desired value')
bq.mockImplementation(() => ({executeQuery}))
describe("Testing consumption moment service function", () => {
it("should call the mock service", () => {
const ms = new MyService(bq,ml)
ms.myFunc(requestBody) //requestBody is a RequestInterface
expect(bq.executeQuery).toHaveBeenCalled
expect(bq.executeQuery).toHaveReturned
});
});
That test passes, so I assume I correctly mocked the bigquery service. But when I try to assert that the value returned is the correct one, I make the test async so that the test wont finish until myFunc is actually done running and I can have a result to compare.
it("should call the mock service", async () => {
const ms = new MyService(bq,ml)
await ms.myFunc(requestBody)
expect(bq.executeQuery).toHaveBeenCalled
expect(bq.executeQuery).toHaveReturned
});
This gets an error: TypeError: this.bigqueryService.executeQuery is not a function
The error points to the line where myFunc calls this.bigqueryService.executeQuery.
I've tried different examples of mocking so that I can mock the call to this function but none got as close as the example above. I also tried to use
jest.spyOn(bq, 'executeQuery')
But that also said that executeQuery wasn't a function: Cannot spy the executeQuery property because it is not a function; undefined given instead
Can someone point me in the right direction here? Is there something I'm missing to make this test work? I thank you all in advance for any help you can give me.
I ended up figuring it out, so if anyone is in the same situation, here is where I found the answer: https://jestjs.io/docs/en/jest-object
The test was fixed like this:
jest.mock('../config-service/logger.service', () => jest.fn())
const ml = require('../config-service/logger.service')
const executeQuery = jest.fn()
describe("Testing service function", () => {
it("should call the mock service", async () => {
jest.mock('../services/bigquery/bigquery.service', () => {
return {
executeQuery: jest.fn(() => 'desired output'),
};
})
const bq = require('../services/bigquery/bigquery.service')
const ms = new MyService(bq,ml)
const p = await ms.myFunc(requestBody) //requestBody is a RequestInterface
expect(bq.executeQuery).toHaveBeenCalled
expect(bq.executeQuery).toHaveReturned
expect(p).toEqual(desired result)
});
});
bq.mockImplementation(() => ({executeQuery}))
Isn't async, try returning a promise
bq.mockImplementation(() => (Promise.resolve({executeQuery})))

Jest mocking a dependency that's instantiated before the module export

I'm trying to test a file which exports one default function, and also instantiates an object before the exported function that needs to remain as the same instance every time the exported function is called.
Here's a simplified version of the module:
import { HttpClient } from '../client'
const client = new HttpClient()
export default (params) => {
const url = 'www.'
// There's a little bit more code here to generate the url based on the params passed in
return client.get(url)
}
I want to test that the url send to the client.get() function is correct, so here's the test:
import myModule from '../myModule'
import { HttpClient } from '../client'
jest.mock('../client')
const mockHttpClient = { get: jest.fn(() => 'test') }
HttpClient.mockImplementation(() => mockHttpClient)
it('should parse the query param string', () => {
console.log(myModule({}))
})
When the test runs, the response from myModule({}) is always undefined.
However, if I move the const client = new HttpClient() line down to just inside the exported function, it works correctly and myModule({}) returns test.
I need the HttpClient to only be defined once, and have the same instance used every time the function is called, so it has to be instantiated outside the function. How can I mock that object creation to return my custom value? Thanks.
This because when you call import {} from '../client' it will immediately invoke new HttpClient(), before you mock the constructor. you could change your mock to
jest.mock('../client', () => ({
HttpClient: jest.fn(() => ({
get: jest.fn(() => 'test'),
}));
}));
but usually anything involve network IO is async, so you might actually need to return a promise like jest.fn(() => Promise.resolve('test')) or jest.fn().mockResolvedValue('test')

How can I test a class which contains imported async methods in it?

This is my first time working with tests and I get the trick to test UI components. Now I am attempting to test a class which has some static methods in it. It contains parameters too.
See the class:
import UserInfoModel from '../models/UserInfo.model';
import ApiClient from './apiClient';
import ApiNormalizer from './apiNormalizer';
import Article from '../models/Article.model';
import Notification from '../models/Notification.model';
import Content from '../models/Link.model';
export interface ResponseData {
[key: string]: any;
}
export default class ApiService {
static makeApiCall(
url: string,
normalizeCallback: (d: ResponseData) => ResponseData | null,
callback: (d: any) => any
) {
return ApiClient.get(url)
.then(res => {
callback(normalizeCallback(res.data));
})
.catch(error => {
console.error(error);
});
}
static getProfile(callback: (a: UserInfoModel) => void) {
return ApiService.makeApiCall(`profile`, ApiNormalizer.normalizeProfile, callback);
}
}
I already created a small test which is passing but I am not really sure about what I am doing.
// #ts-ignore
import moxios from 'moxios';
import axios from 'axios';
import { baseURL } from './apiClient';
import { dummyUserInfo } from './../models/UserInfo.model';
describe('apiService', () => {
let axiosInstance: any;
beforeEach(() => {
axiosInstance = axios.create();
moxios.install();
});
afterEach(() => {
moxios.uninstall();
});
it('should perform get profile call', done => {
moxios.stubRequest(`${baseURL.DEV}profile`, {
status: 200,
response: {
_user: dummyUserInfo
}
});
axiosInstance
.get(`${baseURL.DEV}profile`)
.then((res: any) => {
expect(res.status).toEqual(200);
expect(res.data._user).toEqual(dummyUserInfo);
})
.finally(done);
});
});
I am using moxios to test the axios stuff -> https://github.com/axios/moxios
So which could be the proper way to test this class with its methods?
Introduction
Unit tests are automated tests written and run by software developers to ensure that a section of an application meets its design and behaves as intended. As if we are talking about object-oriented programming, a unit is often an entire interface, such as a class, but could be an individual method.
The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. So if we consider your ApiService.makeApiCall function:
static makeApiCall(
url: string,
normalizeCallback: (d: ResponseData) => ResponseData | null,
callback: (d: any) => any
) {
return ApiClient.get(url)
.then((res: any) => {
callback(normalizeCallback(res.data));
})
.catch(error => {
console.error(error);
});
}
we can see that it has one external resource calling ApiClient.get which should be mocked. It's not entirely correct to mock the HTTP requests in this case because ApiService doesn't utilize them directly and in this case your unit becomes a bit more broad than it expected to be.
Mocking
Jest framework provides great mechanism of mocking and example of Omair Nabiel is correct. However, I prefer to not only stub a function with a predefined data but additionally to check that stubbed function was called an expected number of times (so use a real nature of mocks). So the full mock example would look as follows:
/**
* Importing `ApiClient` directly in order to reference it later
*/
import ApiClient from './apiClient';
/**
* Mocking `ApiClient` with some fake data provider
*/
const mockData = {};
jest.mock('./apiClient', function () {
return {
get: jest.fn((url: string) => {
return Promise.resolve({data: mockData});
})
}
});
This allows to add additional assertions to your test example:
it('should call api client method', () => {
ApiService.makeApiCall('test url', (data) => data, (res) => res);
/**
* Checking `ApiClient.get` to be called desired number of times
* with correct arguments
*/
expect(ApiClient.get).toBeCalledTimes(1);
expect(ApiClient.get).toBeCalledWith('test url');
});
Positive testing
So, as long as we figured out what and how to mock data let's find out what we should test. Good tests should cover two situations: Positive Testing - testing the system by giving the valid data and Negative Testing - testing the system by giving the Invalid data. In my humble opinion the third branch should be added - Boundary Testing - Test which focus on the boundary or limit conditions of the software being tested. Please, refer to this Glossary if you are interested in other types of tests.
The positive test flow flow for makeApiCall method should call normalizeCallback and callback methods consequently and we can write this test as follows (however, there is more than one way to skin a cat):
it('should call callbacks consequently', (done) => {
const firstCallback = jest.fn((data: any) => {
return data;
});
const secondCallback = jest.fn((data: any) => {
return data;
});
ApiService.makeApiCall('test url', firstCallback, secondCallback)
.then(() => {
expect(firstCallback).toBeCalledTimes(1);
expect(firstCallback).toBeCalledWith(mockData);
expect(secondCallback).toBeCalledTimes(1);
expect(secondCallback).toBeCalledWith(firstCallback(mockData));
done();
});
});
Please, pay attention to several things in this test:
- I'm using done callback to let jest know the test was finished because of asynchronous nature of this test
- I'm using mockData variable which the data that ApiClient.get is mocked this so I check that callback got correct value
- mockData and similar variables should start from mock. Otherwise Jest will not allow to out it out of mock scope
Negative testing
The negative way for test looks pretty similar. ApiClient.get method should throw and error and ApiService should handle it and put into a console. Additionaly I'm checking that none of callbacks was called.
import ApiService from './api.service';
const mockError = {message: 'Smth Bad Happened'};
jest.mock('./apiClient', function () {
return {
get: jest.fn().mockImplementation((url: string) => {
console.log('error result');
return Promise.reject(mockError);
})
}
});
describe( 't1', () => {
it('should handle error', (done) => {
console.error = jest.fn();
const firstCallback = jest.fn((data: any) => {
return data;
});
const secondCallback = jest.fn((data: any) => {
return data;
});
ApiService.makeApiCall('test url', firstCallback, secondCallback)
.then(() => {
expect(firstCallback).toBeCalledTimes(0);
expect(secondCallback).toBeCalledTimes(0);
expect(console.error).toBeCalledTimes(1);
expect(console.error).toBeCalledWith(mockError);
done();
});
});
});
Boundary testing
Boundary testing could be arguing in your case but as long as (according to your types definition normalizeCallback: (d: ResponseData) => ResponseData | null) first callback can return null it could be a good practice to check if is the successfully transferred to a second callback without any errors or exceptions. We can just rewrite our second test a bit:
it('should call callbacks consequently', (done) => {
const firstCallback = jest.fn((data: any) => {
return null;
});
const secondCallback = jest.fn((data: any) => {
return data;
});
ApiService.makeApiCall('test url', firstCallback, secondCallback)
.then(() => {
expect(firstCallback).toBeCalledTimes(1);
expect(firstCallback).toBeCalledWith(mockData);
expect(secondCallback).toBeCalledTimes(1);
done();
});
});
Testing asynchronous code
Regarding testing asynchronous code you can read a comprehensive documentation here. The main idea is when you have code that runs asynchronously, Jest needs to know when the code it is testing has completed, before it can move on to another test. Jest provides three ways how you can do this:
By means of a callback
it('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
Jest will wait until the done callback is called before finishing the test. If done() is never called, the test will fail, which is what you want to happen.
By means of promises
If your code uses promises, there is a simpler way to handle asynchronous tests. Just return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail.
async/await syntax
You can use async and await in your tests. To write an async test, just use the async keyword in front of the function passed to test.
it('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
Example
Here you can find a ready to use example of your code
https://github.com/SergeyMell/jest-experiments
Please, let me know if something left unclear for you.
UPDATE (29.08.2019)
Regarding your question
Hi, what can I do to mock ./apiClient for success and error in the same file?
According to the documentation Jest will automatically hoist jest.mock calls to the top of the module (before any imports). It seems that you can do setMock or doMock instead, however, there are issues with mocking this way that developers face from time to time. They can be overridden by using require instead of import and other hacks (see this article) however I don't like this way.
The correct way for me in this case is do split mock defining and implementation, so you state that this module will be mocked like this
jest.mock('./apiClient', function () {
return {
get: jest.fn()
}
});
But the implementation of the mocking function differs depending on scope of tests:
describe('api service success flow', () => {
beforeAll(() => {
//#ts-ignore
ApiClient.get.mockImplementation((url: string) => {
return Promise.resolve({data: mockData});
})
});
...
});
describe('api service error flow', () => {
beforeAll(() => {
//#ts-ignore
ApiClient.get.mockImplementation((url: string) => {
console.log('error result');
return Promise.reject(mockError);
})
});
...
});
This will allow you to store all the api service related flows in a single file which is what you expected as far as I understand.
I've updated my github example with api.spec.ts which implements all mentioned above. Please, take a look.
The unit test term is self-explanatory that you test a unit. A function in complete isolation. Any outside dependencies are mocked. Here if your'e testing makeApiCall function you'll have to stub it's parameters and then mock the ApiClient promise and expect the function to return whatever you're expecting it to return with respect to your mocked and stub parameters.
One thing that people normally forget and which is the most important is to test the negative cases of a function. What will happen if your function throws an error will it break the app. How your function behaves in case something fails. Tests are written to avoid breaking changes in the app.
here is a better guide how to test async functions in JEST which coding examples:
https://www.leighhalliday.com/mocking-axios-in-jest-testing-async-functions
Hope this helps
UPDATE
Mock your ApiClient
for pass case:
jest.mock('./apiClient', () => {
get: jest.fn(() => Promise.resolve(data)) // for pass case
})
for fail case:
jest.mock('./apiClient', () => {
get: jest.fn(() => Promise.reject(false)) // for fail case
})
now call your makeApiCall for both cases once for success and once for fail.
for fail case:
const makeCall = await makeApiCall( <your stub params here> )
expect(makeCall).toThrowError() // note here you can check whatever you have done to handle error. ToThrowError is not a built-in function but just for understanding
I've mostly done testing in Jasmine so this last piece of code is kind of a psuedo code.
I guess what you are asking is how to test ApiService. If this is the case, then mocking the very own thing you want to test would make the unit test pointless.
What I would expect is the following items
You just want to test logic in your own class, not in the library.
You don't want to make an actual network request, this spams the server and make the test slower to run.
If this is the case, then you should mock out some lib to control their behaviour and see how your class behave under those circumstances. And, mock out any operation that involves network IO, make your test faster and less reliant on external resources.
There are a few things you could check with some dependencies mocked out:
delegation, e.g. is axios called once, with the right param?
directly mock the behaviour of the lib, in your case using maxios.
import ApiService, { baseURL } from './apiClient';
describe('ApiService', () => {
let axiosInstance: any;
beforeEach(() => {
axiosInstance = axios.create();
moxios.install();
});
afterEach(() => {
moxios.uninstall();
});
// usually 1 test suite for each method
describe('#getProfile', (done) => {
// mocking behaviour
it('should perform get profile call', () => {
moxios.stubRequest(`${baseURL.DEV}profile`, {
status: 200,
response: {
_user: dummyUserInfo
}
});
ApiService.getProfile((profile) => {
expect(profile).toEqual(dummyUserInfo); // you get what i mean
done();
});
});
// directly mock axios
it('delegates to axios', (done) => {
// you should put this to the top to avoid confusion, it will be hoisted
jest.mock('axios', () => ({
create: jest.fn(() => ({
get: jest.fn(() => Promise.resolve()),
})),
}));
ApiService.getProfile((profile) => {
// do some assertion
expect(axiosInstance.get).toHaveBeenCalledTimes(1);
expect(axiosInstance.get).toHaveBeenCalledWith(url, someParam, youGetIt);
done();
});
});
// rmb to test some error case
it('should throw when param is not correct', (done) => { ... });
});
});

Testing a Jest method that has multiple promises

I am attempting to write a test for a service in my app.
async post(url, params, headers) {
const csrfToken = await this.getCsrfToken().then(res => res.data);
headers.headers['X-CSRF-TOKEN'] = csrfToken;
// console.log(params);
return this.http.post(url, params, headers);
}
The issue I am encountering is I am getting an error that data is not defined. I believe this refers to the csrfToken call (which is just another API call to get this token to append to the header).
I'm not entirely sure how to mock that constant inside jest so I can actually get to my post call. Is there an easy way in jest?
You shouldn't try to mock the constant, you should mock the getCsrfToken instead. Try something like:
import { getCsrfToken, post } from MyClass
it('should work', () => {
// mock method on your class
myMock = jest.fn()
myMock.mockReturnValueOnce(Promise.resolve({
data: {
fakeCsrf
}
})
MyClass.csrfToken = myMock
post('/test', {}, {})
expect(...);
});

Categories

Resources