本文介绍了关于使用nockjs和jest进行诺言/异步单元测试的代码覆盖率问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written a simple unit test for API call using NockJS and Jest for a react application as bellow:

AjaxService.js

AjaxService.js

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

API承诺:

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

使用NockJS进行单元测试:

Unit test using 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(() => {});

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

But when the code-coverage report is generated using Jest --coverage as below:

我们可以看到,在承诺中,成功回调错误回调在单元测试期间不会被调用.当应用程序具有大量API调用时,如何覆盖这部分代码,因为它会影响代码覆盖率?还是我测试不正确?由于我是单元测试的新手,请提供帮助.提前致谢.

We can see that in promise, success callback and error callback is not called during unit test. How to cover this part of code as it affects code-coverage percentage when an application is having numerous API calls? Or am I not testing is properly? Please help as I am new to unit testing. Thanks in advance.

推荐答案

Jest仅在测试期间运行 的情况下才算覆盖行.

Jest counts a line as covered only if it runs during a test.

在这种情况下,您好像在测试过程中正在呼叫getDashboard ...

In this case it looks like you are calling getDashboard during the test...

...但是getDashboard是异步的,测试未等待其完成.

...but getDashboard is asynchronous and the test isn't waiting for it to finish.

这意味着测试将在getDashboard中的异步代码有机会运行并且所有尚未运行的代码未包括在Jest代码覆盖范围内之前同步完成.

This means that the test completes synchronously before the asynchronous code in getDashboard has a chance to run and any code that hasn't run yet is not included in the Jest code coverage.

要确保代码已正确测试并包含在代码范围内,请确保您await getDashboard返回的Promise:

To make sure that code is properly tested and included in the code coverage make sure you await the Promise returned by getDashboard:

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

这篇关于关于使用nockjs和jest进行诺言/异步单元测试的代码覆盖率问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 20:06