Jest spyOn 仅在第二次调用和第三次调用时模拟实现

Sta*_*ley 6 javascript mocking node.js jestjs

我有一个函数,我只想在第二次调用和第三次调用时模拟,但在第一次调用时使用默认实现。我查看了 Jest 文档,有一个函数 mockImplementationOnce 可以用来模拟单个调用的实现。

有没有我可以使用的函数,它会在第一次调用时使用默认实现,并且只模拟第二次和第三次调用?

let functionCalls = 0;
const database = {
  fetchValues() {
    fetchValues();
    fetchValues();
  },
};
jest.spyOn(database, 'fetchValues')
.useDefaultImplementation() // <-- is there such a function?
.mockImplementationOnce(() => 42)
.mockImplementationOnce(() => 42)
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 13

您可以使用mockImplementation方法来模拟默认实现。查看模拟实现

\n\n

例如

\n\n
const database = {\n  fetchValues() {\n    return \'real data\';\n  },\n};\n\ndescribe(\'61450440\', () => {\n  afterEach(() => {\n    jest.restoreAllMocks();\n  });\n  it(\'should pass\', () => {\n    jest\n      .spyOn(database, \'fetchValues\')\n      .mockImplementation(() => \'default\')\n      .mockImplementationOnce(() => \'first call\')\n      .mockImplementationOnce(() => \'second call\');\n\n    console.log(\n      [database.fetchValues(), database.fetchValues(), database.fetchValues(), database.fetchValues()].join(\',\'),\n    );\n  });\n  it(\'should pass too\', () => {\n    jest\n      .spyOn(database, \'fetchValues\')\n      .mockImplementation(() => \'real data\')\n      .mockImplementationOnce(() => \'real data\')\n      .mockImplementationOnce(() => \'first call\')\n      .mockImplementationOnce(() => \'second call\');\n\n    console.log(\n      [database.fetchValues(), database.fetchValues(), database.fetchValues(), database.fetchValues()].join(\',\'),\n    );\n  });\n\n  it(\'should pass 3\', () => {\n    const fetchValuesSpy = jest.spyOn(database, \'fetchValues\');\n    console.log(\'call original fetchValues:\', database.fetchValues());\n    fetchValuesSpy.mockImplementationOnce(() => \'first call\').mockImplementationOnce(() => \'second call\');\n    console.log(\'call mocked fetchValues:\', database.fetchValues(), database.fetchValues());\n    console.log(\'call original fetchValues again:\', database.fetchValues());\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

检测结果:

\n\n
 PASS  stackoverflow/61450440/index.test.ts (13.748s)\n  61450440\n    \xe2\x9c\x93 should pass (20ms)\n    \xe2\x9c\x93 should pass too (1ms)\n    \xe2\x9c\x93 should pass 3 (12ms)\n\n  console.log stackoverflow/61450440/index.test.ts:15\n    first call,second call,default,default\n\n  console.log stackoverflow/61450440/index.test.ts:27\n    real data,first call,second call,real data\n\n  console.log stackoverflow/61450440/index.test.ts:34\n    call original fetchValues: real data\n\n  console.log stackoverflow/61450440/index.test.ts:36\n    call mocked fetchValues: first call second call\n\n  console.log stackoverflow/61450440/index.test.ts:37\n    call original fetchValues again: real data\n\nTest Suites: 1 passed, 1 total\nTests:       3 passed, 3 total\nSnapshots:   0 total\nTime:        15.761s\n
Run Code Online (Sandbox Code Playgroud)\n