我不确定我是否完全理解它,但是如果您需要模拟它以使其始终有效,您应该模拟实现以使其始终返回相同的东西。你可以找到很多关于模拟自定义函数here。
// Mock before importing
jest.mock('./mydir/helper/ageFunc', () => ({
__esModule: true,
default: () => 'Default',
ageFunc : () => 'hardcoded result',
}));
import { ageFunc } from './mydir/helper/ageFunc';
const ageRange = ageFunc(customerPropValues); // ageRange returns 'Hardcode result'
如果不是这种情况,您想要,但只是想检查是否传递了正确的参数,或者收到了正确的结果,您可以执行以下一些操作:
// The mock function was called at least once
expect(ageFunc).toHaveBeenCalled();
// The mock function was called at least once with the specified arguments
expect(ageFunc).toHaveBeenCalledWith(arg1, arg2);
// The last call to the mock function was called with the specified arguments
expect(ageFunc).toHaveBeenLastCalledWith(arg1, arg2);
// All calls and the name of the mock is written as a snapshot
expect(ageFunc).toMatchSnapshot();
有用的链接:link #1link #2
它是如何工作的?
让我们从一个简单的默认模块示例开始:
import a from './path'
我们模拟这个的方式是:
jest.mock('./path')
import a from './path'
此测试文件会将模拟函数读入a 变量。
现在对于您的案例,您有一个命名导出,因此案例有点复杂。
import { a } from './path'
为了模拟这个,我们必须扩展 jest.mock 一点。
jest.mock('./path', () => ({
__esModule: true, // Settings to make it behave as an ECMAScript module
default: () => 'Default', // Mock the default export (import a from './dir')
a: () => 'hardcoded result', // Mock the named export (import { a } from './dir'
}));