How to test axios requests parameters with sinon / chai
Asked Answered
A

1

7

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?

Ailyn answered 11/6, 2018 at 15:27 Comment(6)
sorry, example was bad as it did not call the function! I have updated it now - it is not the exact code as I cannot share that.Ailyn
Could you let me know the console.log(_spy.args) just after myclass.fetch() in the testcode?Interrogate
Have you tried passing it other parameters within your test and them expect them to beEqual? That's the only way I can imagine right now that you would test thatDickson
@YonggooNoh console.log(_spy.args) produces []Ailyn
Turns out, the function I was testing was changed and so was not passing in the parameters.. so in this case, the test was (correctly) failing! I can confirm when using the above framework, _spy.args contains [ [ '/test', { params: { start: '2018-01-01', end: '2018-01-30' } } }. Using _spy.args[0][1].params can access it (though I am sure there is a better way!)Ailyn
I'm voting to close this question as off-topic because the poster understood that he never called the function he wanted to test. Therefore there is nothing to debug or answer.Foetor
S
4

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

Skyscraper answered 20/11, 2019 at 5:32 Comment(2)
this doesn't work when there's then in the axios call, TypeError: Cannot read property 'then' of undefined which is not in the example. why would anyone do axios call without the responseWreak
@FadelTrivandiDipantara It depends if you actually do a petition to an API you aren't in the realm of unit testing anymore, you are doing an integration test.Tricky

© 2022 - 2024 — McMap. All rights reserved.