Unit testing 如何使用jest仅针对某些指定参数模拟函数,而对任何其他参数使用其原始逻辑?
假设我有一个函数:Unit testing 如何使用jest仅针对某些指定参数模拟函数,而对任何其他参数使用其原始逻辑?,unit-testing,jestjs,mocking,Unit Testing,Jestjs,Mocking,假设我有一个函数: function complexCompute(num: number): string { switch(num) { case 1: return '...something...'; case 2: return '...something...'; case 3: return '...something...'; // more cases } 在我想要测试的代码中,它被多次使用,但我想这样模拟它: 当我传递
function complexCompute(num: number): string {
switch(num) {
case 1: return '...something...';
case 2: return '...something...';
case 3: return '...something...';
// more cases
}
在我想要测试的代码中,它被多次使用,但我想这样模拟它:
- 当我传递参数
为num
时,1
返回模拟字符串complexCompute
my-mock-string1
- 当我传递任何其他参数时,它使用其原始逻辑
jest.mock('./complexCompute')
模拟的complexCompute
没有原始逻辑。我必须为参数1
定义模拟值,还必须为其他参数重写整个逻辑
有什么方法可以做到这一点吗?访问您可以使用的模拟模块的实际实现 以下是两个例子:
模拟整个模块
jest.mock('./complexCompute', () => {
const actual = jest.requireActual('./complexCompute').default;
return {
default: (arg: number): string => arg === 1 ? 'my-mock-string1' : actual(arg)
}
})
将自动模拟与
你不喜欢吗?为什么在使用1调用complexCompute时,您只想将您正在测试的内容与它的实现隔离开来?为什么不完全解耦呢?谢谢!好像是在开玩笑。唯一的办法是反应性的。我设法使用了'jest-when',使它更加灵活:
beforeach(()=>{when(complexCompute).mockImplementation(jest.requireActual('./complexCompute').default);})
,然后在测试用例中,我可以使用when(complexCompute).calledWith(1).mockedReturnValue(mockedValue)
来模拟我所关心的参数
import complexCompute from './complexCompute';
jest.mock('./complexCompute')
complexCompute.mockImplementation((arg) => {
return arg === 1
? 'my-mock-string1'
: jest.requireActual('./complexCompute').default(arg)
});