如何在模块中只模拟一个函数?
How to mock only one function in the module?
我只想模拟 bar
模块中的 bar
函数。
但是当我 运行 测试时,它似乎也嘲笑了 init 函数。
有没有办法只模拟 bar 函数?
// bar.ts:
export const bar = () => {};
export const init = () => {};
// foo.ts
import { bar } from './bar';
export const foo () => {
const result = bar();
return result;
}
// foo.spec.ts
import { bar, init } from './bar';
import { foo } from './foo';
jest.mock('./bar', () => ({ bar: () => { console.log('in bar'); } }));
beforeAll(() => {
init();
});
it('should', () => {
const result = foo();
expect(..).toBe(..)
});
是:
jest.mock('./bar', () => ({
...jest.requireActual('./bar'),
bar: jest.fn()
}));
根据经验,模拟函数应该是 Jest 间谍,这允许断言调用并在需要时更改实现。
我只想模拟 bar
模块中的 bar
函数。
但是当我 运行 测试时,它似乎也嘲笑了 init 函数。
有没有办法只模拟 bar 函数?
// bar.ts:
export const bar = () => {};
export const init = () => {};
// foo.ts
import { bar } from './bar';
export const foo () => {
const result = bar();
return result;
}
// foo.spec.ts
import { bar, init } from './bar';
import { foo } from './foo';
jest.mock('./bar', () => ({ bar: () => { console.log('in bar'); } }));
beforeAll(() => {
init();
});
it('should', () => {
const result = foo();
expect(..).toBe(..)
});
是:
jest.mock('./bar', () => ({
...jest.requireActual('./bar'),
bar: jest.fn()
}));
根据经验,模拟函数应该是 Jest 间谍,这允许断言调用并在需要时更改实现。