且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在每个测试中更改 jest 模拟函数的返回值?

更新时间:2023-11-03 20:40:40

您可以模拟模块,使其返回间谍并将其导入您的测试:

You can mock the module so it returns spies and import it into your test:

import {navigationEnabled, guidanceEnabled} from '../../../magic/index'

jest.mock('../../../magic/index', () => ({
    navigationEnabled: jest.fn(),
    guidanceEnabled: jest.fn()
}));

然后您可以使用 mockImplementation

navigationEnabled.mockImplementation(()=> true)
//or
navigationEnabled.mockReturnValueOnce(true);

在下一个测试中

navigationEnabled.mockImplementation(()=> false)
//or
navigationEnabled.mockReturnValueOnce(false);