如何用sinon / chai测试axios请求参数

时间:2018-06-11 15:27:32

标签: javascript sinon chai sinon-chai

我正在尝试使用sinon / chai / mocha测试axios调用的参数,以确认某些参数的存在(理想情况下它们是有效的日期)。

示例代码(在类 myclass 中)

fetch() {
  axios.get('/test', { params: { start: '2018-01-01', end: '2018-01-30' } })
  .then(...);
}

示例测试

describe('#testcase', () => {
  let spy;
  beforeEach(() => {
    _spy = sinon.spy(axios, "get");
  });
  afterEach(() => {
    _spy.restore();
  });
  it('test fetch', () => {
    myclass.fetch();
    expect(_spy).to.have.been.calledWith('start', '2018-01-01');
    expect(_spy).to.have.been.calledWith('end', '2018-01-30');
  });
});

但是,我尝试了很多选项,包括匹配器,expect(axios.get) ... expect(..).satisfygetCall(0).args和axios-mock-adapter,但我无法弄清楚如何执行此操作。我错过了什么?

1 个答案:

答案 0 :(得分:0)

这是单元测试解决方案,您应该使用sinon.stub,而不是sinon.spy。使用sinon.spy将调用原始方法,这意味着axios.get将发送真实的HTTP请求。

例如 index.ts

import axios from "axios";

export class MyClass {
  fetch() {
    return axios.get("/test", {
      params: { start: "2018-01-01", end: "2018-01-30" }
    });
  }
}

index.spec.ts

import { MyClass } from "./";
import sinon from "sinon";
import axios from "axios";
import { expect } from "chai";

describe("MyClass", () => {
  describe("#fetch", () => {
    let stub;
    beforeEach(() => {
      stub = sinon.stub(axios, "get");
    });
    afterEach(() => {
      stub.restore();
    });
    it("should send request with correct parameters", () => {
      const myclass = new MyClass();
      myclass.fetch();
      expect(
        stub.calledWith("/test", {
          params: { start: "2018-01-01", end: "2018-01-30" }
        })
      ).to.be.true;
    });
  });
});

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

 MyClass
    #fetch
      ✓ should send request with correct parameters


  1 passing (8ms)

---------------|----------|----------|----------|----------|-------------------|
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/50801243