[我正在尝试使用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(..).satisfy
,getCall(0).args
和axios-mock-adapter,但是我不知道该怎么做。我想念什么?
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