Jest酶单元测试axios api服务的覆盖范围

问题描述

我是开玩笑的,酶单位测试。我有以下代码,它按预期工作

组件

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);
        });
    });
});

因此,测试将成功运行,但是在覆盖率报告中看不到覆盖率。

enter image description here

任何帮助将不胜感激。

解决方法

那是因为在您的getProductList()中,您在成功获取数据后返回了res.data,然后在componentDidMount()中检查了getProductList()的响应状态是否等于'Success' ,因此本质上您正在做的是这样:

axios.get("/products/listProducts").then(res => {
    if (res.data.status==='Success') {...}
});

难怪这条路永远不会走。