gpt4 book ai didi

javascript - Jest : How to mock a library in node_modules?

转载 作者:行者123 更新时间:2023-11-29 23:01:30 26 4
gpt4 key购买 nike

我正在尝试为使用 node-forge 的代码编写测试。出于某种原因,当我调用 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)

奇怪的是,当我尝试模拟我自己的文件时,这种策略非常有效。

模拟第 3 方库的正确方法是什么?

最佳答案

你试过吗?关于此的更多信息 here .

jest.mock('node-forge', () => ({
md: {
sha256: {
create: () => ({
update: () => {},
digest: () => ({
toHex: () => 'foobar'
}),
}),
},
},
}));

关于javascript - Jest : How to mock a library in node_modules?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55524547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com