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 的例子?
您可以使用jest.mock(moduleName,factory,options)来模拟axios函数。
例如
\n\nindex.js:
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}\nRun Code Online (Sandbox Code Playgroud)\n\nindex.test.js:
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});\nRun Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\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\nRun Code Online (Sandbox Code Playgroud)\n\n源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59873406
\n| 归档时间: |
|
| 查看次数: |
1455 次 |
| 最近记录: |