测试时拦截axios请求

时间:2019-09-05 14:37:30

标签: node.js axios sinon chai

我正在测试软件,并且想验证发送到API的请求是否具有正确的数据。此特定方法创建具有某些数据,标头等的请求,然后通过axios向外部API发送该请求。示例代码:

myFunction() {
    const data = {
        example: 'my data'
    };

    const headers = {
        'content-type': 'application/json'
    }

    const request = {
        method: 'POST',
        baseUrl: 'http://myawesome-site.com',
        url: '/api/path',
        headers,
        data,
    }

    return axios(request)
        .then(res => ...do something)
        .catch(err => ...do something else)
}

我想知道是否有一种使用chaisinon的方法来拦截axios调用并仅访问“请求”对象以验证发送的数据,我不知道不在乎响应。

1 个答案:

答案 0 :(得分:0)

这是一个单元测试解决方案,您应该使用sinon.stub

  

当您要防止直接调用特定方法时(可能是因为它触发了不希望的行为,例如XMLHttpRequest或类似的

例如 index.ts

import axios, { AxiosRequestConfig } from 'axios';

exports.myFunction = function myFunction() {
  const data = {
    example: 'my data'
  };

  const headers = {
    'content-type': 'application/json'
  };

  const request: AxiosRequestConfig = {
    method: 'POST',
    baseURL: 'http://myawesome-site.com',
    url: '/api/path',
    headers,
    data
  };

  return exports
    .axios(request)
    .then(res => console.log('do something'))
    .catch(err => console.log('do something else'));
};

exports.axios = axios;

index.spec.ts

const mod = require('./');
import sinon from 'sinon';
import { expect } from 'chai';

describe('myFunction', () => {
  afterEach(() => {
    sinon.restore();
  });
  it('should send request', async () => {
    const mResponse = { status: 200 };
    const axiosStub = sinon.stub(mod, 'axios').resolves(mResponse);
    const logSpy = sinon.spy(console, 'log');
    await mod.myFunction();
    expect(
      axiosStub.calledWith({
        method: 'POST',
        baseURL: 'http://myawesome-site.com',
        url: '/api/path',
        headers: {
          'content-type': 'application/json'
        },
        data: {
          example: 'my data'
        }
      })
    ).to.be.true;
    expect(logSpy.calledWith('do something')).to.be.true;
  });

  it('should handle request error', async () => {
    const mError = new Error('network error');
    const axiosStub = sinon.stub(mod, 'axios').rejects(mError);
    const logSpy = sinon.spy(console, 'log');
    await mod.myFunction();
    expect(
      axiosStub.calledWith({
        method: 'POST',
        baseURL: 'http://myawesome-site.com',
        url: '/api/path',
        headers: {
          'content-type': 'application/json'
        },
        data: {
          example: 'my data'
        }
      })
    ).to.be.true;
    expect(logSpy.calledWith('do something else')).to.be.true;
  });
});

覆盖率100%的单元测试结果:

  myFunction
do something
    ✓ should send request
do something else
    ✓ should handle request error


  2 passing (14ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 index.spec.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57807855

相关问题