繁体   English   中英

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

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

我有 node.js 组件名称 controller.js,它有一个使用 axios 和选项调用 api 服务的函数,它还具有用于错误处理的 catch 函数。 我无法存根 axios 函数以便通过单元测试来覆盖它。

下面是 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' });                   
                    }
                 }
             });
  }
}

下面是我的 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();
    });

});

在这里,我无法存根 axios 函数和捕获函数以进行错误处理。 因此无法覆盖纽约市 axios 成功和捕获功能的代码。 请帮忙..

首先,不能使用try...catch语句来捕获异步代码,如果要这样做,则需要使用async/await等待 promise 被解析或拒绝。 此外,由于您已经捕获了axios异常并且没有重新抛出它,因此您不需要try...catch

其次,您正在尝试存根axios函数,该函数是从axios模块导入的独立函数。 诗浓不支持。 您需要使用Link Seams ,因此我们将使用proxyquire来构建我们的接缝。

例如

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 :

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

单元测试结果:

  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