[英]Jest: How to mock a library in node_modules?
我正在嘗試為使用 node-forge 的代碼編寫測試。 出於某種原因,當我調用forge.md.sha256.create();
時,測試掛起forge.md.sha256.create();
:
import forge from "node-forge";
const privateKey = "foo";
const storagePin = "bar";
const md = forge.md.sha256.create();
md.update(privateKey + storagePin);
const metadataKey = md.digest().toHex();
作為一種解決方法,我試圖模擬該方法的實現,以便它只返回一個硬編碼的字符串:
import forge from "node-forge";
jest.mock("node-forge");
forge.mockImplementation(() => {
return {
md: {
sha256: {
create: () => {
return {
update: () => {},
digest: () => {
toHex: () => "foobar";
}
};
}
}
}
};
});
// tests
但是,我的測試一直失敗:
TypeError: _nodeForge2.default.mockImplementation is not a function
at Object.<anonymous> (src/redux/epics/authentication-epic.test.js:20:27)
at new Promise (<anonymous>)
at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
at processTicksAndRejections (internal/process/next_tick.js:81:5)
奇怪的是,當我嘗試模擬自己的文件時,這種策略非常有效。
嘲笑 3rd 方圖書館的正確方法是什么?
你試過這樣嗎? 更多關於這里。
jest.mock('node-forge', () => ({
md: {
sha256: {
create: () => ({
update: () => {},
digest: () => ({
toHex: () => 'foobar'
}),
}),
},
},
}));
default
導出不是函數,因此Jest
自動模擬不會用模擬函數替換默認導出...
...但default
導出是一個對象。
...雖然您無法更改導入的值,但您可以更改它們所引用的對象。
所以你可以將對象上的md
屬性設置為你的模擬:
import forge from 'node-forge';
jest.mock('node-forge');
const toHex = jest.fn(() => 'foobar');
const digest = jest.fn(() => ({ toHex }));
const update = jest.fn();
forge.md = { // <= set the md property to your mock
sha256: {
create: jest.fn(() => ({
update,
digest
}))
}
};
test('code uses the mock', () => {
require('./path to your code'); // <= the mock will be used in the required code
expect(forge.md.sha256.create).toHaveBeenCalled(); // Success!
expect(update).toHaveBeenCalledWith('foobar'); // Success!
expect(digest).toHaveBeenCalled(); // Success!
expect(toHex).toHaveBeenCalled(); // Success
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.