【发布时间】:2019-09-18 05:57:06
【问题描述】:
我正在尝试通过替换 react-native-randombytes 来编写一个有趣的单元测试,因为它使用了一些 NativeModules。
我的错误信息:
Test suite failed to run
TypeError: Cannot read property 'seed' of undefined
> 1 | const RandomBytes = jest.genMockFromModule('react-native-randombytes');
| ^
2 |
3 | const randomBytes = (l) => {
4 | let uint8 = new Uint8Array(l);
at seed (node_modules/react-native-randombytes/index.js:15:21)
at Object.init (node_modules/react-native-randombytes/index.js:57:1)
at Object.genMockFromModule (__mocks__/react-native-randombytes.js:1:26)
我将文件react-native-randombytes 放在__mocks__ 文件夹中node_modules 旁边
const RandomBytes = jest.genMockFromModule('react-native-randombytes');
const randomBytes = (l) => {
let uint8 = new Uint8Array(l);
uint8 = uint8.map(() => Math.floor(Math.random() * 90)+10);
return uint8;
};
const seed = randomBytes(4096);
RandomBytes.randomBytes = randomBytes;
RandomBytes.seed = seed;
export default RandomBytes;
我打开了我想模拟的库,我发现它不是一个类,而是在它的 index.js 文件的末尾执行以下代码部分。 link
function init () {
if (RNRandomBytes.seed) {
let seedBuffer = toBuffer(RNRandomBytes.seed)
addEntropy(seedBuffer)
} else {
seedSJCL()
}
}
似乎使用 jest.genMockFromModule 会触发 init 函数,所以整个模拟失败了。在选择使用哪种模拟方法时我应该考虑哪些因素?在文档中,它列出了各种方法,但没有明确建议何时使用哪些方法。
我应该使用 jest.fn() 吗?
请指教。
更新 1:
我在测试文件中尝试了以下内容
jest.mock('react-native-randombytes');
const randomBytes = jest.fn().mockImplementation((l) => {
let uint8 = new Uint8Array(l);
uint8 = uint8.map(() => Math.floor(Math.random() * 90)+10);
return uint8;
});
结果:它不起作用。它有同样的错误。
更新 2:在 mock 中更改我的文件,如下所示
const R = jest.genMockFromModule('react-native-randombytes');
R.randomBytes = (l) => {
let uint8 = new Uint8Array(l);
uint8 = uint8.map(() => Math.floor(Math.random() * 90)+10);
return uint8;
};
R.init = () => {};
export default R;
结果:同样的错误信息。它仍然是原始的 react-native-randombytes。
更新 3:就像更新 1,但有一些变化 灵感来自post
jest.genMockFromModule('react-native-randombytes');
// eslint-disable-next-line import/first
import randomBytes from 'react-native-randombytes';
randomBytes.mockImplementation((l) => {
let uint8 = new Uint8Array(l);
uint8 = uint8.map(() => Math.floor(Math.random() * 90)+10);
return uint8;
});
结果:同样的错误信息。
【问题讨论】:
标签: javascript react-native jestjs