我的问题是关于如何模拟从另一个文件导入默认的 jest 函数。
我想测试的是使用函数来启用功能的组件(Features.js
)
我使用jest.fn()模拟了这个函数,并尝试使用mockReturnValueOnce更改值
如下所示。
mocks/features.js
export default function isFeatureEnabled (featureName) {
return true // want to test both true/false cases
}
测试.spec.js
jest.mock('__mocks__/features.js', () => ({
isFeatureEnabled: jest.fn()
}))
describe('isFeatureEnabled', () => {
it('isFeatureEnabled=[true]', () => {
isFeatureEnabled.mockReturnValueOnce(true)
// some tests
})
it('isFeatureEnabled=[false]', () => {
isFeatureEnabled.mockReturnValueOnce(false)
// some tests
})
})
当我运行测试时,出现错误:mockReturnValueOnce is not a function
。这个stackoverflow question启发我以这种方式实现,但我仍然不知道如何让它发挥作用。
最佳答案
你已经很接近了。
这是一个简单的工作示例,演示了您正在尝试执行的操作:
features.js
export default function isFeatureEnabled (featureName) {
// this is the actual implementation...
return true // ...but for the example just return true
}
__mock__/features.js
export default jest.fn(() => true); // default export is mock that returns true
代码.js
import isFeatureEnabled from './features';
export const funcToTest = () => isFeatureEnabled() ? 'enabled' : 'not enabled';
代码.test.js
import { funcToTest } from './code';
import isFeatureEnabled from './features';
jest.mock('./features'); // use the manual mock
describe('funcToTest', () => {
it('isFeatureEnabled=[true]', () => {
isFeatureEnabled.mockReturnValueOnce(true);
expect(funcToTest()).toBe('enabled'); // Success!
})
it('isFeatureEnabled=[false]', () => {
isFeatureEnabled.mockReturnValueOnce(false);
expect(funcToTest()).toBe('not enabled'); // Success!
})
})
关于reactjs - 如何模拟从另一个文件导入的 jest 函数作为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55419415/