admin管理员组文章数量:1357394
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 bination of current Node, ES6, and Jest?
worker.ts (dependency):
export default async () => {
const response = await fetch(";);
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(";);
expect(response.status).toBe(200);
const result2 = await doWork();
expect(result2.myItem).toStrictEqual("abc");
expect(mockedFetch).toBeCalledTimes(2);
});
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 bination of current Node, ES6, and Jest?
worker.ts (dependency):
export default async () => {
const response = await fetch("http://example2");
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");
expect(response.status).toBe(200);
const result2 = await doWork();
expect(result2.myItem).toStrictEqual("abc");
expect(mockedFetch).toBeCalledTimes(2);
});
Share
Improve this question
asked May 25, 2022 at 19:58
individualtermiteindividualtermite
3,78517 gold badges50 silver badges80 bronze badges
1
- is there any way to have this behavior in a bination of current Node, ES6, and Jest? I have answered to a similar question here. – Marco Luzzara Commented May 30, 2022 at 5:54
1 Answer
Reset to default 5 +100First, 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./facebook/jest/issues/2567
- Change
const originalFetch = jest.requireActual('node-fetch')
to
const originalFetch = jest.requireActual('node-fetch').default;
本文标签: javascriptGet original implementation during jest mockStack Overflow
版权声明:本文标题:javascript - Get original implementation during jest mock - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744039661a2580429.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论