This content originally appeared on DEV Community and was authored by Rafa FERIAH
When working with JavaScript, it's so common to import external or internal libraries. Sometimes in order to implement modularity and reusability in our project, sometimes to avoid implementing features that have been already developed by a third party.
Today we're gonna see how to mock these libraries when testing the code are using them with Jest suite.
First of all let's suppose we have the following code:
maths.js
export const sum = (a, b) => a + b
export const substract = (a, b) => a - b;
app
import { sum, substract } from './math.mjs'
const sumResult = sum(2, 1);
const substractResult = substract(2, 1);
Given that code, we could have two scenarios:
- Mock the full "import", i.e., the full library.
- Mock only one of the methods but keep the original code of the other one
So let's see each case:
Mocking the full library
To mock the full library, we just need to mock one of the method (the other one will remain undefined
) or we can mock all the methods. The mocking technique is indifferent, it depends on what are we testing.
// mock only one method
jest.mock('../math', () => ({
sum: jest.fn(),
}));
// mock only one method (with implementation)
jest.mock('../math', () => ({
sum: jest.fn().mockImplementation(() => '5'),
}));
// mock all methods
jest.mock('../math', () => ({
sum: jest.fn(),
substract: jest.fn(),
}));
Mocking only one of the imported methods
As we said before, we can import only one of the methods and keep the original implementation for the rest of the methods
In the following example, we are mocking the substrack
method but keep the original implementation of the rest of the library, in this case, the add
method
jest.mock('../math', () => {
const originalMathLib = jest.requireActual('../math');
return {
...originalMathLib,
substract: jest.fn(),
};
});
It's very important to include this code at the very top of our testing file, before any other import
. These mocks MUST be the firsts lines of our file.
This content originally appeared on DEV Community and was authored by Rafa FERIAH
Rafa FERIAH | Sciencx (2023-04-24T21:01:33+00:00) Mock imported modules in Jest. Retrieved from https://www.scien.cx/2023/04/24/mock-imported-modules-in-jest/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.