pt2*_*t2t 15 javascript reactjs jestjs axios
我在嘲笑我的 api 调用时遇到错误
TypeError: Cannot read property 'mockResolvedValue" of undefined
Run Code Online (Sandbox Code Playgroud)
并且无法弄清楚原因。我正在使用 jest 来测试我的 api fetch 调用函数。
这是我要导出的功能:
//file amData.jsx
const axios = require('axios');
async function fetchAssetManagerSummary() {
const response = await axios.get("https://www.exampleUrl.com");
return response.data;
}
module.exports = fetchAssetManagerSummary;
Run Code Online (Sandbox Code Playgroud)
这是我的测试文件
const fetchAssetManagerSummary = require('./amData');
const axios = require('axios');
jest.mock("axios");
it("returns the object from fetch", async () => {
axios.get.mockResolvedValue({
data: [
{
userId: 1,
id: 1,
title: 'test'
}
]
})
const data = await fetchAssetManagerSummary();
console.log("data", data)
});
Run Code Online (Sandbox Code Playgroud)
我得到的错误:
wen*_*jun 22
由于您已经模拟了axios
该类,因此模拟 axios.get 返回值的方法之一是这样做:
axios.get = jest.fn().mockResolvedValue({
data: [
{
userId: 1,
id: 1,
title: 'test'
}
]
});
.
.
expect(axios.get).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)
或者,您可以监视 axios.get(),并提供模拟返回值:
jest.spyOn(axios, 'get').mockResolvedValueOnce({
data: [
{
userId: 1,
id: 1,
title: 'test'
}
]
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13703 次 |
最近记录: |