Smu*_*Web 5 javascript sinon chai sinon-chai
我试图使用sinon/chai/mocha来测试axios调用的参数,以确认某些参数的存在(理想情况下它们是有效的日期).
示例代码(在类myclass中)
fetch() {
axios.get('/test', { params: { start: '2018-01-01', end: '2018-01-30' } })
.then(...);
}
Run Code Online (Sandbox Code Playgroud)
示例测试
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');
});
});
Run Code Online (Sandbox Code Playgroud)
不过,我已经尝试了许多选择,包括的匹配,expect(axios.get)
... expect(..).satisfy
,getCall(0).args
和爱可信-模拟适配器,但我无法弄清楚如何做到这一点.我错过了什么?
这是单元测试解决方案,您应该使用sinon.stub
,而不是sinon.spy
。使用时sinon.spy
会调用原来的方法,这意味着axios.get
会发送一个真正的HTTP请求。
例如\n index.ts
:
import axios from "axios";\n\nexport class MyClass {\n fetch() {\n return axios.get("/test", {\n params: { start: "2018-01-01", end: "2018-01-30" }\n });\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\nindex.spec.ts
:
import { MyClass } from "./";\nimport sinon from "sinon";\nimport axios from "axios";\nimport { expect } from "chai";\n\ndescribe("MyClass", () => {\n describe("#fetch", () => {\n let stub;\n beforeEach(() => {\n stub = sinon.stub(axios, "get");\n });\n afterEach(() => {\n stub.restore();\n });\n it("should send request with correct parameters", () => {\n const myclass = new MyClass();\n myclass.fetch();\n expect(\n stub.calledWith("/test", {\n params: { start: "2018-01-01", end: "2018-01-30" }\n })\n ).to.be.true;\n });\n });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\n\n MyClass\n #fetch\n \xe2\x9c\x93 should send request with correct parameters\n\n\n 1 passing (8ms)\n\n---------------|----------|----------|----------|----------|-------------------|\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |\n---------------|----------|----------|----------|----------|-------------------|\nAll files | 100 | 100 | 100 | 100 | |\n index.spec.ts | 100 | 100 | 100 | 100 | |\n index.ts | 100 | 100 | 100 | 100 | |\n---------------|----------|----------|----------|----------|-------------------|\n
Run Code Online (Sandbox Code Playgroud)\n\n源代码:https ://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/50801243
\n 归档时间: |
|
查看次数: |
983 次 |
最近记录: |