简体   繁体   中英

Code coverage concern on promise/asynchronous unit testing using nockjs and jest

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

AjaxService.js

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

API Promise:

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

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

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

在此处输入图片说明

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 counts a line as covered only if it runs during a test .

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM