简体   繁体   中英

How to mock JSON import Jest TypeScript

I want to mock a.json file using Jest for unit testing in Typescript.

I'm currently using this global mock inside jest.config.js file. 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 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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