Ashley Coolman
Ashley Coolman

Reputation: 11585

Sinon fakeServer with mocha and axios

I'm trying to get sinon.fakeServer to make axios return a faked response. Instead of returning the mocked payload, I can see the network request 404s or does a timeout trying to go to the actual URL.

My setup:

  describe('test call', () => {
    var server;
    beforeEach(() => {
      server = sinon.fakeServer.create();
      server.respondWith(
        "https://my.domain.com/myresource",
        [200, { "Content-Type": "application/json" }, "[]"]
      );
      server.autoRespond = true
    });
    it('returns empty array', done => {
      axios
        .get('https://my.domain.com/myresource')
        .then(res => {
          expect(true).to.equal(true);
          done()
        })
        .catch(err=>{
          console.log(err.message);
          expect(false).to.equal(true);
          done();
        });
    });
    afterEach(() => {
      server.restore();
    });
  })  

Upvotes: 0

Views: 5119

Answers (1)

chrysanthos
chrysanthos

Reputation: 1418

It seems that your execution environment is NodeJS, even though it's not mentioned. Others had the same issue - have a look here.

Also the Sinon team mentions that it's outside their scope since XHR are supposed to work correctly in the browser, where their fake server works as expected as it stubs the XHR object.

Axios is using a different library for making requests when running on the server, so this scenario cannot work by default. There are specific mocking libs for axios like moxios as an alternative.

Upvotes: 2

Related Questions