Jest:模拟导入JSON文件

Ant*_*amp 25 unit-testing jestjs react-native

我目前正在测试我的一个React组件,如下所示:

it('renders correctly', () => {
  const tree = renderer.create(<Scene {...props} />).toJSON();
  expect(tree).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)

我的组件Scene导入setting.json文件.我在我的本地实例上有该文件,但我没有在我的CI实例上推送它.因此,当它尝试导入它时,找不到该文件.

有没有办法在我的测试中模拟这个文件?

And*_*rle 33

您可以使用moduleNameMapper您的jest设置将导入指向模拟的json文件.

{
  "moduleNameMapper": {
    "setting.json": "<rootDir>/__mocks__/setting.json"
  }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以jest.mock在测试中使用直接模拟文件,请注意您必须添加{ virtual: true }参数.

jest.mock('path/to/setting.json', ()=>({
  settings: 'someSetting'
}), { virtual: true })
Run Code Online (Sandbox Code Playgroud)

  • 请注意,该路径是相对于测试文件的。 (4认同)
  • 我想模拟一个实际上并不存在的“虚拟”文件。为此,需要选项`{ virtual: true}`。示例:`jest.mock('path/to/file, () =&gt; ({ foo: 'bar'}), { virtual: true })`。谢谢@andreas-köberle (4认同)

spe*_*.sm 5

对于那些希望以 形式模拟 JSON 的人Array,只需从回调中返回一个数组即可。

jest.mock('./data.json', () => ([1, 2, 3]));
Run Code Online (Sandbox Code Playgroud)

您还可以返回其他有效的 JSON 类型:ObjectStringNumberBooleanNull