我想知道如何模拟导入的对象,以便用Jest返回假值。
在这种情况下,我想将默认超时值(5000
)覆盖为1000
,以使函数崩溃
// config.ts
export const config = {
request: {
timeout: 5000,
},
};
// Test file
import * as config from './config';
describe('Requests', () => {
beforeEach(() => {
jest.mock('./config');
});
afterEach(() => {
jest.resetAllMocks();
});
it('Force timeout value', () => {
jest.mock('./config');
config.request.timeout.mockReturnValueOnce(1000);
expect(config.request.timeout).toEqual(1000); // FAIL: returns 5000 instead of 1000
});
});
谢谢!
答案 0 :(得分:2)
在这种情况下,您必须使用Require
而不是import(ESM)。
// config.ts
export const config = {
request: {
timeout: 5000
}
}
测试文件如下所示:
// Test file
describe('greetings', () => {
beforeEach(() => jest.resetModules())
describe('hello', () => {
describe('when the language is set to galician', () => {
it('returns galician for hi', () => {
jest.mock('./config', () => ({ request: { timeout: 1000 } }))
const { request } = require('./config')
expect(request.timeout).toEqual(1000)
})
})
describe('when the language is not set to galician', () => {
it('returns hi', () => {
jest.mock('./config', () => ({ request: { timeout: 2000 } }))
const { request } = require('./config')
expect(request.timeout).toEqual(2000)
})
})
})
})
参考-https://medium.com/trabe/mocking-different-values-for-the-same-module-using-jest-a7b8d358d78b