【发布时间】:2020-10-22 12:56:36
【问题描述】:
所以假设我有一个名为“config.js”的文件:
export const DELAY_SECONDS = 5;
在进行测试时:
// Ignore the delay when doing the tests.
jest.mock("/path/to/config", () => ({ DELAY_SECONDS: 0 }))
但我也想测试一下原始值是否有效:
it('should work with delay', () => {
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
我怎样才能恢复那个模拟?或者有没有更好的方法来实现模拟?
我在下面尝试了一些方法,但它们都不起作用:
it('should work with delay', () => {
jest.unmock() // Doesn't work at all, don't even know what does this method do.
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
it('should work with delay', () => {
jest.mock("/path/to/config", () => ({ DELAY_SECONDS: 5 })) // Call the mock again doesn't work
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
it('should work with delay', () => {
const config = require("/path/to/config").default;
config.DELAY_SECONDS = 5; // Won't work, as it is a constant, cannot modify
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
【问题讨论】:
标签: javascript jestjs mocking