使用 axios 构造函数时模拟 axios

Uri*_*lar 3 mocking jestjs axios

我有一个 API 实用函数,它使用构造函数符号调用 axios:

axios({
   method,
   url: `${BASE_URL}/${url}`,
   data
});
Run Code Online (Sandbox Code Playgroud)

我想用 Jest 来模拟这个,但不太确定如何做。我只能模拟特定的 axios 函数(get、post 等)。

有没有人有一个以这种方式使用 axios 的例子?

sli*_*wp2 5

您可以使用jest.mock(moduleName,factory,options)来模拟axios函数。

\n\n

例如

\n\n

index.js:

\n\n
import axios from \'axios\';\n\nexport function main() {\n  const BASE_URL = \'https://stackoverflow.com\';\n  const url = \'api\';\n  const data = {};\n  return axios({\n    method: \'GET\',\n    url: `${BASE_URL}/${url}`,\n    data,\n  });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

index.test.js:

\n\n
import { main } from \'.\';\nimport axios from \'axios\';\n\njest.mock(\'axios\', () => jest.fn());\n\ndescribe(\'59873406\', () => {\n  it(\'should pass\', async () => {\n    const mResponse = { data: \'mock data\' };\n    axios.mockResolvedValueOnce(mResponse);\n    const response = await main();\n    expect(response).toEqual(mResponse);\n    expect(axios).toBeCalledWith({ method: \'GET\', url: \'https://stackoverflow.com/api\', data: {} });\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

100%覆盖率的单元测试结果:

\n\n
 PASS  src/stackoverflow/59873406/index.test.js\n  59873406\n    \xe2\x9c\x93 should pass (7ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |      100 |      100 |      100 |      100 |                   |\n index.js |      100 |      100 |      100 |      100 |                   |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        5.362s, estimated 13s\n
Run Code Online (Sandbox Code Playgroud)\n\n

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59873406

\n

  • 当我这样做时,我收到一条错误消息,指出 axios.mockResolvedValueOnce 不是函数。包“jest”:“^29.3.1”,,“axios”:“0.27.2” (3认同)