How to unit test promise rejection in React and Jest - javascript

I am trying to write a unit test for a react component. It's a fairly standard component which calls a promise-returning method and uses 'then' and 'catch' to handle the resolution. My test is trying to validate that it calls the correct method when the promise is rejected however despite following what i believe is a standard patttern, I cannot get jest to validate the call. I have listed the relevant files here and have also put up a github sample, which is linked at the bottom of the question. That sample is simply a new react app created using npx and the files below added in.
Here is my example component:
import React from 'react';
import api from '../api/ListApi';
class ListComponent extends React.Component {
constructor(props) {
super(props);
this.fetchListSuccess = this.fetchListSuccess.bind(this);
this.fetchListFailed = this.fetchListFailed.bind(this);
}
fetchList() {
api.getList()
.then(this.fetchListSuccess)
.catch(this.fetchListFailed);
}
fetchListSuccess(response) {
console.log({response});
};
fetchListFailed(error) {
console.log({error});
};
render() {
return(<div>Some content</div>);
};
}
export default ListComponent;
Here is the api class (note, the api doesnt exist if you run the app, its just here for example):
const getList = () => fetch("http://someApiWhichDoesNotExist/GetList");
export default { getList };
And here is the test case:
import ListComponent from './ListComponent';
import api from '../api//ListApi';
describe('ListComponent > fetchList() > When the call to getList fails', () => {
it('Should call fetchListFailed with the error', async () => {
expect.hasAssertions();
//Arrange
const error = { message: "some error" };
const errorResponse = () => Promise.reject(error);
const componentInstance = new ListComponent();
api.getList = jest.fn(() => errorResponse());
componentInstance.fetchListFailed = jest.fn(() => { });
//Act
componentInstance.fetchList();
//Assert
try {
await errorResponse;
} catch (er) {
expect(componentInstance.fetchListFailed).toHaveBeenCalledWith(error);
}
});
});
The problem is that the test is not executing the catch block, so, in this case, the expect.hasAssertions() is failing the test. Can anyone help me understand the catch block is not executing? Wrapping the await in the try block and asserting in the catch seems to be a standard pattern in the docs but I am fairly new to Js and React and am obviously doing something wrong.
Here is the sample project on GitHub. Any help would be greatly appreciated =)

In your console:
const errorResponse = () => Promise.reject();
await errorResponse;
//() => Promise.reject()
You're awaiting a function, not the result of the call to that function. You want to:
await errorResponse();
EDIT:
In addition to that, the rest of your test is confusing. I believe you actually want to test what happens when the fetchList method of your component is called, and it fails, I assume. So you need to call it in your test, and await it's response:
Update your component's fetchList method to return the promise.
await componentInstance.fetchList() instead of await errorResponse()
Because you catch the error in fetchList you'll never enter the catch or the try...catch so your final test should look like this:
Test:
//Arrange
const error = { message: "some error" };
const errorResponse = () => Promise.reject(error);
const componentInstance = new ListComponent();
api.getList = jest.fn(() => errorResponse());
componentInstance.fetchListFailed = jest.fn(() => { });
//Act
await componentInstance.fetchList();
expect(componentInstance.fetchListFailed).toHaveBeenCalledWith(error);
Component:
fetchList() {
return api.getList()
.then(this.fetchListSuccess)
.catch(this.fetchListFailed);
}

My two cents, with my own case in a React native app:
In my component I have:
const handleRedirect = React.useCallback(() => {
client.clearStore()
.then(navigation.push('SomeScreen'))
.catch(e => logger.error('error', e));
}, []);
My test is this one, where I want to test if the promise is rejected:
it('should throw an exception on clearStore rejected', async () => {
const client = {
clearStore: jest.fn()
};
const error = new Error('clearStore failed');
client.clearStore.mockReturnValue(Promise.reject(error));
expect.assertions(1);
await expect(client.clearStore())
.rejects.toEqual(Error('clearStore failed'));
});

Related

mock a service with Jest

Trying to write a test to provide code coverage for the following code :
note : there are other functions in the service but just listing one for brevity.
export const service = {
getById: async (id) => {
const url = `/api/customers/${id}/names`
const {data} = await axios.get(url, axiosOptions);
return data;
}
I'm attempting to simply provide code coverage with this test:
note : I have attempted to use require instead of import but that does not seem to work.
import {service} from './requests';
it("mocks the getById function", () => {
service.getById = jest.fn();
expect(service.getById.mock).toBeTruthy();
}
This test passes however seems to provide no code coverage.
I've attempted to mock out the axios call but I seem to get nowhere as examples I've found of implementations are not working for me currently.
Does anyone have ideas and an example how I could provide code coverage for the service please?
Update : to sonEtLumiere's answer
jest.mock('./service', () => ({
getById: jest.fn().mockResolvedValue({ data : "hello"}),
}));
describe('test', () => {
it('mocks the service", async () => {
service.getById.mockResolvedValue({data: "hello});
const data = await service.getById(1);
expect(data).toEqual({data:"hello"});
})
})
Currently getting back error :
Cannot read properties of undefined (reading 'getById')
Any thoughts on why I'm getting this error?
To mock a service using Jest, you can use the jest.mock() function to create a mocked version of the service. For example:
jest.mock('path/to/service', () => ({
getById: jest.fn().mockResolvedValue({ /* mocked data */ }),
}));
Then, in your test file, you can import the mocked version of the service and use the mock property on the function to control its behavior. For example, you can use .mockResolvedValue to set the resolved value of the function, or use .mockRejectedValue to make the function throw an error.
import { service } from 'path/to/service';
describe('test', () => {
it('mocks the service', async () => {
service.getById.mockResolvedValue({ /* mocked data */ });
const data = await service.getById(1);
expect(data).toEqual({ /* mocked data */ });
});
});
I do agree with #Lin Du's comment, if you want to test service.getById, you should be mocking what the method depends on, in this case axios.get.
But following along with your question, the issue is that the named export in ./requests is an object containing the getById property which is the method you want to test. So jest.mock should look like:
jest.mock("./requests.js", () => ({
service: {
getById: jest.fn(),
},
}))
Then your test will pass as you expected:
it("mocks the getById function", async () => {
service.getById.mockResolvedValueOnce({ data: "hello" })
const data = await service.getById(1)
expect(data).toEqual({ data: "hello" })
})
But again, if you want to test a method and have proper coverage, what you need to mock is the method's dependency, not the method itself, e.g:
import { service } from "./requests"
import axios from "axios"
jest.mock("axios")
test("service.getById", async () => {
axios.get.mockResolvedValueOnce({ data: "hello" })
const result = await service.getById(1)
expect(result).toBe("hello")
})

Trouble mocking ES6 Module using jest.unstable_mockModule

I'm attempting to mock a call to a class instance function on an ES6 module being imported by the code under test. I've followed the progress of the ES6 support and eventually stumbled onto this PR https://github.com/facebook/jest/pull/10976 which mentioned that in 27.1.1 support for jest.unstable_mockModule was added. I upgraded my version of Jest to take advantage and while the test doesn't error, it also doesn't seem to actually mock the module either.
This is the module under test:
// src/Main.mjs
import Responder from './Responder.mjs'
import Notifier from './Notifier.mjs'
export default {
async fetch(request, environment, context) {
let response
try {
response = new Responder(request, environment, context).respond()
} catch (error) {
return new Notifier().notify(error)
}
return response
}
}
Here is the test:
// test/Main.test.mjs
import { jest } from '#jest/globals'
import main from '../src/Main.mjs'
describe('fetch', () => {
test('Notifies on error', async () => {
const mockNotify = jest.fn();
jest.unstable_mockModule('../src/Notifier.mjs', () => ({
notify: mockNotify
}))
const notifierMock = await import('../src/Notifier.mjs');
await main.fetch(null, null, null)
expect(mockNotify).toHaveBeenCalled()
})
})
I'm trying to mock the call to Notify to expect it to have been called and while this will run, it raises an exception from inside the Notifier.notify() that is supposed to be mocked, so it appears that it isn't being mocked at all.
What am I missing? Any help is much appreciated. 🙏
I believe it's because you're importing main at the start of the file. You need to do a dynamic import the same way as Notifier.mjs
// test/Main.test.mjs
import { jest } from '#jest/globals'
describe('fetch', () => {
test('Notifies on error', async () => {
const mockNotify = jest.fn();
jest.unstable_mockModule('../src/Notifier.mjs', () => ({
notify: mockNotify
}))
const notifierMock = await import('../src/Notifier.mjs');
const main = await import('../src/Main.mjs');
await main.fetch(null, null, null)
expect(mockNotify).toHaveBeenCalled()
})
})

Jest: Does not allow mocked method to be overwritten

Given the following test code:
import { MyParentClass } from "MyParentClass";
import { MyClass } from "MyClass";
MyClass.prototype.post = jest.fn(() => Promise.resolve({token: '12345'}));
it('first test: this test will be successful tested ✓', async() => {
const myParentClass = new MyParentClass();
await expect(myParentClass.run()).toEqual({token: '12345'});
})
it('second test: this test will fail ×', async () => {
MyClass.prototype.post = jest.fn(() => Promise.reject({message: 'An error ocurred'}));
const myParentClass = new MyParentClass();
await expect(myParentClass.run()).rejects.toEqual({message: 'success'});
})
The "run" method internally makes use of the 'MyClass' class and its "post" method. When I run a code like this, for my second test, I get a message like the following:
"Received promise resolved instead of rejected"
I understand that when the answer for the "post" method is globally defined, it will always take that value, but I also understand that in the second test I am overwriting the behavior of that method, why don't you take it into account?
I know I can also use jest.doMock, but I don't understand the documentation well, could someone help me understand it to apply it to my example?
Using asyncFn as so will solve the problem, and additionally simplify the test by making it read in chronological order.
import asyncFn from '#asyncFn/jest';
describe('myParentClass', () => {
let parentClass;
let runPromise;
beforeEach(() => {
parentClass = new MyParentClass();
parentClass.post = asyncFn();
runPromise = myParentClass.run();
});
it('first test: this test will be successful tested ✓', () => {
parentClass.post.resolve({ token: '12345' });
return expect(runPromise).resolves.toEqual({ token: '12345' });
})
it('second test: this test will fail ×', () => {
parentClass.post.reject({ message: 'An error occured'} );
return expect(runPromise).rejects.toEqual({ message: 'An error occured' });
});
});
You can use mockImplementationOnce or mockReturnValueOnce since you've already converted post to a jest mock function. So you could do something like this on your 2nd test:
it('second test: this test will fail ×', async () => {
MyClass.prototype.post.mockReturnValueOnce(Promise.reject({message: 'An error ocurred'}));
const myParentClass = new MyParentClass();
await expect(myParentClass.run()).rejects.toEqual({message: 'An error ocurred'});
})

Testing Imported Function with Parameter using Jest Mock Function / Jest spyOn

I'm trying to write a unit test for a Node.js project's logic using Jest.
However, most documentations only provide a case for importing a module or class, however, in my case, my module only contains functions.
So far I know that there are mainly three ways to test a function in Jest:
1) jest.fn()
2) jest.spyOn
3) jest.mock('path')
I have tried all three but none work.
I wanted to test if the function returns a correct value(string) when called.
I tried many different
Here's my code: (I will show short snippets of my code in the later parts)
getDefApCode.ts
export function getDefApCode(code: string) {
switch (code) {
case 'BKK':
return 'NRT'
case 'CTX':
return 'ICN'
case 'SIN':
return 'TPE'
default:
return code
}
}
export function getDefaultDepartureCode(code: string) {
return code ? getDefaultLocationCode(code) : 'LHR'
}
export function getDefaultDestinationCode(code: string) {
return code ? getDefaultLocationCode(code) : 'ZRH'
}
getDefAPCode.spec.ts >> Pattern 1 (using required + jest.fn)
import { Connection, getConnection, getConnectionOptions } from "typeorm";
import { bootstrap, dbConnection } from "../../../src/app";
import { TourSearchParamsFactory } from "../../helpers/typeOrmFactory";
import * as getDefAPCode from "../../../src/controllers/logic/getDefAPCode";
describe("Logic Test", () => {
beforeAll(async () => {
await dbConnection(15, 3000);
});
afterAll(async () => {
const conn = getConnection();
await conn.close();
});
it("should get a default location code", async () => {
const getLocation = require('../../../src/controllers/logic/getDefAPCode');
const code = jest.fn(code => 'BKK');
const getCode = getLocation(code);
expect(getCode).toHaveBeenCalled();
});
});
Error Message:
TypeError: getLocation is not a function
getDefAPCode.spec.ts >> Pattern 2 (using spyON)
import { Connection, getConnection, getConnectionOptions } from "typeorm";
import { bootstrap, dbConnection } from "../../../src/app";
import { TourSearchParamsFactory } from "../../helpers/typeOrmFactory";
import * as getDefaultLocationCode from "../../../src/controllers/logic/getDefaultLocationCode";
describe("Logic Test", () => {
beforeAll(async () => {
await dbConnection(15, 3000);
});
afterAll(async () => {
const conn = getConnection();
await conn.close();
});
const { getDefaultLocationCode, getDefaultDepartureCode, getDefaultDestinationCode } = require('../../../src/controllers/logic/getDefaultLocationCode');
it("should get a default location code", async () => {
const spy = jest.spyOn(getDefaultLocationCode, 'getDefaultLocationCode');
getDefaultLocationCode.getDefaultLocationCode('AKJ');
expect(spy).toHaveBeenCalled();
});
});
These are some error messages appear when I tried a different pattern (I didn't keep track of all of the test code pattern, will add the test code pattern once I fixed docker)
Error Message:
Cannot spy the getDefaultLocationCode property because it is not a function; undefined given instead
31 | const spy = jest.spyOn(getDefaultLocationCode, 'getDefaultLocationCode');
Past Error Messages
error TS2349: This expression is not callable.
Type 'typeof import("/app/src/controllers/logic/getDefAPCode")' has no call signatures.
another one
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has type: string
Received has value: "NRT"
I figured out that I don't have to use mock function in this case.
I stored argument in a variable and then I use the variable instead using a string directly.
Here's how I edit my test code
it("should get a default location code", () => {
const code = 'BKK';
expect(code).toHaveBeenCalled();
});

JestJS: Async test isn't stopped

I got two problems with this jest test:
Is it possible to define the Content collection only once instead of doing that inside of the test?
I do get this error:
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.
I don't see why my async code weren't stopped...
import resolvers from 'resolvers/'
import Db from 'lib/db'
const db = new Db()
describe('Resolver', () => {
let token
beforeAll(async () => {
await db.connect()
})
beforeEach(async () => {
token = 'string'
await db.dropDB()
})
afterAll(async () => {
await db.connection.close()
})
describe('articleGetContent()', () => {
test('should return dataset', async () => {
// SETUP
const Content = db.connection.collection('content')
const docs = [{
// some content...
}]
await Content.insertMany(docs)
// EXECUTE
const result = await resolvers.Query.articleGetContent({}, {
id: '123,
language: 'en'
}, {
token
})
// VERIFY
expect.assertions(1)
expect(result).toBeDefined()
})
})
})
resolver
import { articleGetContent } from '../models/article'
export default {
Query: {
articleGetContent: async (obj, { id }, { token }) => articleGetContent(id, token)
}
}
This is how my db class looks like
db.js
export default class Db {
constructor (uri, callback) {
const mongo = process.env.MONGO || 'mongodb://localhost:27017'
this.mongodb = process.env.MONGO_DB || 'testing'
this.gfs = null
this.connection = MongoClient.connect(mongo, { useNewUrlParser: true })
this.connected = false
return this
}
async connect (msg) {
if (!this.connected) {
try {
this.connection = await this.connection
this.connection = this.connection.db(this.mongodb)
this.gfs = new mongo.GridFSBucket(this.connection)
this.connected = true
} catch (err) {
console.error('mongo connection error', err)
}
}
return this
}
async disconnect () {
if (this.connected) {
try {
this.connection = await this.connection.close()
this.connected = false
} catch (err) {
console.error('mongo disconnection error', err)
}
}
}
async dropDB () {
const Content = this.connection.collection('content')
await Content.deleteMany({})
}
}
Related to the second question I hope you've found some issues on github about it.
In general, the issue is described in the debug log.
Jest works with promises, as a result, you shouldn't leave any async operations in any status except resolved.
In your case, you have your DB connection opened so you need to implement another method disconnect for your DB class, this link to docs will help you, but I guess you have it already as it's not the full db.js file ( I see some custom method dropDB. Main idea here is to have it in afterAll hook:
afterAll(() => db.disconnect());
Great example at the bottom of the page
What about the first question, it really depends on what you are doing in your method dropDB. If you're running method for dropping collection, you could store the reference to this collection somewhere outside and use it as it will automatically create the new one, but it would be great to see this method.
Additionally, your async test was created in a wrong way, you could read more here for example in my Update. You need to run this function in the beginning of the test: expect.assertions(number)
expect.assertions(number) verifies that a certain number of assertions
are called during a test. This is often useful when testing
asynchronous code, in order to make sure that assertions in a callback
actually got called.

Categories