Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何使用jest仅针对某些指定参数模拟函数,而对任何其他参数使用其原始逻辑?_Unit Testing_Jestjs_Mocking - Fatal编程技术网

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)
});