简体   繁体   English

使用 Mocha、sinon 和 chai 进行 Node.js axios 单元测试

[英]Node.js axios unit testing using Mocha, sinon and chai

I have node.js component name controller.js which have a function that calls api service using axios with options and it also have catch function for error handling.我有 node.js 组件名称 controller.js,它有一个使用 axios 和选项调用 api 服务的函数,它还具有用于错误处理的 catch 函数。 I am not able to stub axios function so as to cover it by unit testing.我无法存根 axios 函数以便通过单元测试来覆盖它。

Below is controller.js component.下面是 controller.js 组件。

const axios = require('axios');
export.getData = function(req, res, next) {
  try {
     const options = {
            method: 'GET',
            headers: headers,
            url,
            params: queryParams
     };  
     axios(options).then(function (response) {
            res.json(response.data);
        })
            .catch(function (error) {
                if (error && error.response) {
                    if (error.response.status === 401) {
                        res.status(500).send({ error: true, message: 'There seems to be an issue, please try after sometime' });                   
                    }
                 }
             });
  }
}

below is my controller.test.js下面是我的 controller.test.js

const chai = require('chai');
const assert = chai.assert;
const axios = require('axios');
const sinon = require('sinon');
const controller = require('../controllersr');

describe("controller API testing", () => {

it("should call getMarketId function and return status 200 on success", function (done) {
        const req = { };
        const res =  { json: {greet: "hello"}, status: 200};
        var mockStub = sinon.stub(axios, 'get').resolves(res);
        controller.getData(req, res);
        assert.equal(res.status, 200);
        mockStub.restore();
        done();
    });

});

Here, I am not able to stub axios funtion and catch function for error handling.在这里,我无法存根 axios 函数和捕获函数以进行错误处理。 And thus unable to cover the code for axios success and catch function in NYC.因此无法覆盖纽约市 axios 成功和捕获功能的代码。 Please help..请帮忙..

First, You can't use try...catch statement to catch asynchronous code, if you want to do so, you need to use async/await to wait for the promise to be resolved or rejected.首先,不能使用try...catch语句来捕获异步代码,如果要这样做,则需要使用async/await等待 promise 被解析或拒绝。 Besides, since you already caught the axios exception and didn't re-throw it, you don't need to try...catch .此外,由于您已经捕获了axios异常并且没有重新抛出它,因此您不需要try...catch

Second, you are trying to stub axios function which is a standalone function imported from axios module.其次,您正在尝试存根axios函数,该函数是从axios模块导入的独立函数。 Sinon does NOT support that.诗浓不支持。 You need to use Link Seams , so we will be using proxyquire to construct our seams.您需要使用Link Seams ,因此我们将使用proxyquire来构建我们的接缝。

Eg例如

controller.js : controller.js

const axios = require('axios');

exports.getData = function (req, res, next) {
  const options = {
    method: 'GET',
    headers: headers,
    url,
    params: queryParams,
  };
  axios(options)
    .then(function (response) {
      res.json(response.data);
    })
    .catch(function (error) {
      if (error && error.response) {
        if (error.response.status === 401) {
          res.status(500).send({ error: true, message: 'There seems to be an issue, please try after sometime' });
        }
      }
    });
};

controller.test.js : controller.test.js :

const sinon = require('sinon');
const proxyquire = require('proxyquire');

describe('controller API testing', () => {
  it('should call getMarketId function and return status 200 on success', async () => {
    const req = {};
    const res = { json: sinon.stub(), status: 200 };
    const axiosStub = sinon.stub().resolves({ data: { greet: 'hello' } });
    const controller = proxyquire('./controller', {
      axios: axiosStub,
    });
    await controller.getData(req, res);
    sinon.assert.calledWithExactly(axiosStub, {
      method: 'GET',
      headers: {},
      url: 'http://localhost:3000/api',
      params: {},
    });
    sinon.assert.calledWithExactly(res.json, { greet: 'hello' });
  });
});

unit test result:单元测试结果:

  controller API testing
    ✓ should call getMarketId function and return status 200 on success (1306ms)


  1 passing (1s)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |    62.5 |        0 |   66.67 |    62.5 |                   
 controller.js |    62.5 |        0 |   66.67 |    62.5 | 15-17             
---------------|---------|----------|---------|---------|-------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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