Get original implementation during jest mock - javascript

I'm trying to temporarily mock node-fetch in an ESM module while still retraining the original implementation so I can access a real endpoint's value. However, this errors with "Must use import to load ES Module." I recognize jest support for ESM is still pending - is there any way to have this behavior in a combination of current Node, ES6, and Jest?
worker.ts (dependency):
export default async () => {
const response = await fetch("http://example2.org");
return await response.json()
}
main.test.ts:
import { jest } from "#jest/globals";
jest.mock("node-fetch", () => {
return Promise.resolve({
json: () => Promise.resolve({ myItem: "abc" }),
})
})
import doWork from './worker.js';
import mockedFetch from 'node-fetch';
const originalFetch = jest.requireActual('node-fetch') as any;
test("Ensure mock", async () => {
const result = await doWork();
expect(result.myItem).toStrictEqual("abc");
expect(mockedFetch).toBeCalledTimes(1);
const response = await originalFetch("http://www.example.org");
expect(response.status).toBe(200);
const result2 = await doWork();
expect(result2.myItem).toStrictEqual("abc");
expect(mockedFetch).toBeCalledTimes(2);
});

First, Jest doesn't support jest.mock in ESM module for tests
Please note that we currently don't support jest.mock in a clean way
in ESM, but that is something we intend to add proper support for in
the future. Follow this issue for updates.
This is reasonable because import has different semantic than require. All imports are hoisted and will be evaluated at module load before any module code.
So in your case because you are using jest.mock I assume that your test code are transformed. In this case, if you want to use non "CommonJS" package, you should transform it too. You can change transformIgnorePatterns in jest config to []. It means that all packages from node_modules will go through transform. If it's too aggressive, you can pick specific modules which ignore like this "transformIgnorePatterns": [ "node_modules/(?!(node-fetch))" ] but don't forget about transitive dependencies. ;)
Add/change in jest config
"transformIgnorePatterns": []
jest.mock accept module factory which should returns exported code. In your case, you should write it like this.
jest.mock("node-fetch", () => {
return {
__esModule: true,
default: jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ myItem: "abc" }),
})
),
};
});
If you have error
The module factory of jest.mock() is not allowed to reference any out-of-scope variables
just remove jest from import and use it as global variable or import it inside the module factory function
https://github.com/facebook/jest/issues/2567
Change const originalFetch = jest.requireActual('node-fetch') to
const originalFetch = jest.requireActual('node-fetch').default;

Related

How to mock an axios configuration module?

I have a module which configures axios:
// config/axiosConfig.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:8080/api/v1'
});
export default instance;
And a module that uses this to make api calls:
// store/actions.ts
import axiosInstance from 'config/axiosConfig';
export const fetchUsers = () => (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
dispatch(loading(true));
return axiosInstance.get('/users')
.then(res => {
dispatch(loading(false));
dispatch(fetched(res.data));
})
.catch(err => dispatch(error(true)));
}
...
I want to mock the axios config file to test my api file. I've tried many many ways but nothing works. I thought it would be as simple as
// store/actions.test.ts
import axiosInstance from 'config/axiosConfig';
jest.mock('config/axiosConfig');
axiosConfig.get.mockResolvedValue({users: mockUserList});
...
But I guess that's not how it works.
Edit: The approach in my question works when I put axiosConfig.get.mockResolvedValue({users: mockUserList}); inside of the test, not right under the mock call.
Try this out (Put this at the top of the file or at the top inside beforeAll or beforeEach depending on what you prefer):
jest.mock('config/axiosConfig', () => ({
async get(urlPath) {
return {
users: mockUserList,
};
},
}));
This is a simple mock using a factory function. To use a mock everywhere, jest provides a better way to avoid repeating yourself. You create a __mocks__ directory and inside that, you can create your module and then override many of the builtins. Then, you can get away with just the following code.
// file.test.ts
jest.mock('fs')
// Rest of your testing code below
Take a look at the official docs to learn more about this.
If this doesn't work, then the module resolution setup in jest.config.js and tsconfig.js might be different.

Calling React/Webpack module code from Node

I have a custom NextJS webpack config where I call a script that gets executed at build-time in the Node runtime (not in the browser):
module.exports = {
webpack: (config, options) => {
if (options.isServer) {
require("./some-script.js")
}
return config
},
}
What the script does doesn't really matter, but I would like to import some code from my React application (that gets executed in the browser, except for SSR, but that's beside the point).
const fs = require("fs");
const getImages = require("../utils/img");
(() => {
// writes something to disk
})();
When I do this I get this error message: SyntaxError: Cannot use import statement outside a module. This makes sense because I use require for const getImages = require("../utils/img"); but this file is part of the React client-side codebase which uses ES6 import/export modules:
const getImages = () => {
// return something
};
export default getImages;
How can I achieve this? Meaning, how can I call client-side import/export code from a Node.js require script?
Try and convert the required files to use require and module.exports to import and export respectively
const getImages = () => {
// return something
};
module.exports = getImages;

Jest mock module for single import

When using jest with ES6 modules and babel-jest, all the jest.mock calls are hoisted.
Let's say I'd like to mock fs module for the tested class, but preserve the original implementation for the rest of the modules (for example some utils that I use during the test).
Consider the following example:
class UnderTest {
someFunction(){
fs.existsSync('blah');
}
}
class TestUtility {
someOtherFunction(){
fs.existsSync('blahblah');
}
}
the test:
it('Should test someFunction with mocked fs while using TestUtility'', () => {
testUtility.someOtherFunction(); // Should work as expected
underTest.someFunction(); // Should work with mock implementation of 'fs'
})
Now, one would expect that with the following approach the fs module will be mocked for UnderTest but not for TestUtility.
import {TestUtility} from './test-utility';
jest.mock('fs');
import {UnderTest } from './under-test';
However, due to the hoisting, fs module will be mocked for all the modules (which is undesirable).
Is there any way to achieve the described behavior?
To opt out from mocking a module in a test jest.doMock(moduleName, factory, options) and jest.dontMock(moduleName) should be used.
jest.doMock(moduleName, factory, options)
When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
jest.dontMock(moduleName)
When using babel-jest, calls to unmock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
So in your case I would try something like
beforeEach(() => {
jest.resetModules();
});
it('Should test someFunction with mocked fs while using TestUtility'', () => {
jest.dontMock('fs');
testUtility.someOtherFunction(); // Should work as expected
jest.doMock('fs', () => {
return ... // return your fs mock implementation;
});
underTest.someFunction(); // Should work with mock implementation of 'fs'
})
You should probably use jest's requireActual:
const fs = jest.requireActual('fs'); // Unmockable version of jest
class TestUtility {
someOtherFunction(){
fs.existsSync('blahblah');
}
}
From the documentation:
Jest allows you to mock out whole modules in your tests, which can be useful for testing your code is calling functions from that module correctly. However, sometimes you may want to use parts of a mocked module in your test file, in which case you want to access the original implementation, rather than a mocked version.

How to Mock non-default import using Jest

How can I mock a function that is being imported inside the file that contains the function I am testing?
without putting it in the mocks folder.
// FileIWantToTest.js
import { externalFunction } from '../../differentFolder';
export const methodIwantToTest = (x) => { externalFunction(x + 1) }
I need to make sure that externalFunction is called and its called with the correct arguments.
Seems super simple but the documentation doesn't cover how to do this without mocking the module for all the files in the test by putting the mocks in the mocks folder.
The solution: I need to take my jest.mock call outside of any test or any other function because jest needs to hoist it. Also for named exports like in my case I also have to use the following syntax:
jest.mock('../../differentFolder', () => ({
__esModule: true,
externalFunction: jest.fn(),
}));
One of the easiest approaches is to import the library and use jest.spyOn to spy on the method:
import { methodIwantToTest } from './FileIWantToTest';
import * as lib from '../../differentFolder'; // import the library containing externalFunction
test('methodIwantToTest', () => {
const spy = jest.spyOn(lib, 'externalFunction'); // spy on externalFunction
methodIwantToTest(1);
expect(spy).toHaveBeenCalledWith(2); // SUCCESS
});

Using requireActual isn't requiring the actual version of module, in a Jest test

I have a Jest test file like the following:
// utils.test.js
let utils = require('./utils')
jest.mock('./utils')
test('print items', () => {
utils.printItems(['a'])
expect(utils.getImage).toHaveBeenLastCalledWith('a.png')
})
test('get image', () => {
utils = require.requireActual('./utils')
// `utils` is still mocked here for some reason.
expect(utils.getImage('note.png')).toBe('note')
})
And a mock like this:
// __mocks__/utils.js
const utils = require.requireActual('../utils');
utils.getImage = jest.fn(() => 'abc');
module.exports = utils;
Yet as you can see in my comment in the second test, utils is still the mocked version rather than the actual version of the module. Why is that? How can I get it to be the actual version, rather than the mocked version?
You still get the mocked utils module in your second test because you have actually required it inside the manual mock (__mocks__/utils.js), which in Jest's cache is still referenced as a mock that should be returned due to jest.mock() being at the top most scope.
A way to fix it is either to not use the module in a manual mock, or update your second test to unmock and require a new version of it. For example:
test('get image', () => {
jest.unmock('./utils')
const utils = require.requireActual('./utils')
// `utils` is now the original version of that module
expect(utils.getImage('note.png')).toBe('note')
})

Categories