我刚开始开玩笑酶单元测试。我有下面的代码,它正在按预期工作
组件
import productService from './../../../productService';
constructor(props) {
super(props);
this.productService = new productService();
}
componentDidMount() {
this.productService.getProductList().then(res => {
if (res.status === "Success") {
/// Some actions
} else {
/// Some actions
}
});
}productService.js
import axios from 'axios';
class productService {
constructor() {
this.state = {
apiUrl: process.env.REACT_APP_API_URL
}
}
getProductList() {
return axios.get(this.state.apiUrl + "products/listProducts")
.then(res => {
return res.data;
}).catch(err => {
return err;
});
}
}
export default productService;我尝试过axios-mock-adapter来模拟API及其响应。
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
describe('User List Component Unit Tests', () => {
var mock = new MockAdapter(axios);
mock.onGet("/products/listProducts").reply(200, {
"status": "Success",
"data": [...]
});
it('Should trigger the product list api', () => {
wrapper.find('myComponent').instance().componentDidMount();
axios.get("/products/listProducts").then(function (response) {
console.log(response);
});
});
});因此,测试将成功运行,但我在覆盖报告中看不到覆盖范围。

任何帮助都将不胜感激。
发布于 2020-08-15 07:52:33
这是因为在您的getProductList()中,您在成功获取时返回res.data,然后在componentDidMount()中检查getProductList()的响应状态是否等于'Success',所以实际上您要做的是:
axios.get("/products/listProducts").then(res => {
if (res.data.status==='Success') {...}
});难怪这条路从来不走。
https://stackoverflow.com/questions/63419322
复制相似问题