简体   繁体   English

如何模拟 JSON 导入 Jest TypeScript

[英]How to mock JSON import Jest TypeScript

I want to mock a.json file using Jest for unit testing in Typescript.我想使用 Jest 模拟 a.json 文件以在 Typescript 中进行单元测试。

I'm currently using this global mock inside jest.config.js file.我目前在 jest.config.js 文件中使用这个全局模拟。 And this is working fine:这工作正常:

    'package.json': '<rootDir>/__tests__/tasks/__mocks__/data.json'

But I want to mock it locally, inside my test class.但我想在我的测试类中本地模拟它。

This didn't work for me:这对我不起作用:

jest.mock('../../package.json', () => ({
    package : { name: '__name__', 'version': '__version__'};
}), { virtual: true })

you can mock out the class and assign the default export of that file to a variable as follows:您可以模拟该类并将该文件的默认导出分配给变量,如下所示:

jest.mock('../../utils/api/api');
const FakeClass = require('../someFile.js').default;

then access calls to a function on your mock class like this:然后像这样访问对模拟类上的函数的调用:

FakeClass.prototype.myFunc.mock.calls

have you try the following?你试过以下吗?

const packageJson = require('../../package.json);
 jest.mock(packageJson, () => ({
     package : { name: '__name__', 'version': '__version__'};
 }), { virtual: true })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM