I am trying to test the parameters of an axios call using sinon / chai / mocha, to confirm the existence of certain parameters (and ideally that they are valid dates with moment).
Example code (in class myclass)
fetch() {
axios.get('/test', { params: { start: '2018-01-01', end: '2018-01-30' } })
.then(...);
}
Example test
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');
});
});
However, I have tried many options including matchers, expect(axios.get)
... expect(..).satisfy
, getCall(0).args
and axios-mock-adapter, but I cannot figure out how to do this. What am I missing please?
import apis from './apis'; jest. mock('axios'); // This overwrites axios methods with jest Mock import axios from 'axios'; describe('Test Apis', () => { describe('getResource', () => { describe('with success', () => { const url = 'http://test-url.com'; const onComplete = jest.
Here is the unit test solution, you should use sinon.stub
, not sinon.spy
. Use sinon.spy
will call the original method which means axios.get
will send a real HTTP request.
E.g.
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;
});
});
});
Unit test result with 100% coverage:
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 | |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/50801243
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With