使用 nockjs 和 jest 进行 Promise/异步单元测试的代码覆盖率问题

Sur*_*A J 4 javascript code-coverage reactjs jestjs nock

我使用 NockJS 和 Jest 为 React 应用程序编写了一个简单的 API 调用单元测试,如下所示:

AjaxService.js

export const AjaxService = {
    post: (url, data, headers) => {
        return axios({
            method: "POST",
            url: url,
            headers: headers || { "content-type": "application/json" },
            data: data
        });
    },
};
Run Code Online (Sandbox Code Playgroud)

API承诺:

export const getDashboard = (request) => {
  return AjaxService.post(API_DASHBOARD_URL + "/getDashboard", request
  ).then(
    response => {
      return response.data;
    },
    (error) => {
      return error.response.data;
    }
  )
};
Run Code Online (Sandbox Code Playgroud)

使用NockJS进行单元测试:

nock(baseUrl)
    .post(subUrl, request)
    .reply(200, response);

getDashboard(request)
    .then(resp => {
        let compareVal = getNestedObject(resp, keyToCompare);
        let actualVal = getNestedObject(response, keyToCompare);
        expect(compareVal).to.equal(actualVal);
    })
    .then(() => {});
Run Code Online (Sandbox Code Playgroud)

但是当使用 Jest 生成代码覆盖率报告时,--coverage如下所示:

在此输入图像描述

我们可以看到,在promise中,单元测试时并没有调用成功回调错误回调。当应用程序有大量 API 调用时,如何覆盖这部分代码,因为它会影响代码覆盖率?或者我没有正确测试?请帮助,因为我是单元测试的新手。提前致谢。

Bri*_*ams 5

Jest仅当某行在测试期间运行时才将其计为已覆盖。

在这种情况下,您似乎getDashboard在测试期间打电话......

...但是getDashboard是异步的,测试不会等待它完成。

这意味着测试在异步代码getDashboard有机会运行之前同步完成,并且任何尚未运行的代码不包含在Jest代码覆盖率中。

为了确保代码经过正确测试并包含在代码覆盖率中,请确保await返回:PromisegetDashboard

test('getDashboard', async () => {  // <= async test function
  nock(baseUrl)
    .post(subUrl, request)
    .reply(200, response);

  await getDashboard(request)  // <= await the Promise
    .then(resp => {
      let compareVal = getNestedObject(resp, keyToCompare);
      let actualVal = getNestedObject(response, keyToCompare);
      expect(compareVal).to.equal(actualVal);
    })
})
Run Code Online (Sandbox Code Playgroud)