How to use Sinon.js FakeXMLHttpRequest with superagent?

1.7k views Asked by At

I am trying to test one of the React Flux actions that makes a request to the server.

// AppActions.js
fetchMovies(date) {
    this.dispatch(date);
    request
      .get('/api/movies')
      .query(date)
      .end((err, res) => {
        if (!res.ok) {
          this.actions.fetchMoviesFail(res.body);
        } else {
          this.actions.fetchMoviesSuccess(res.body);
        }
      });
  }

In my Flux store tests I have something like the following:

  // AppStore-test.js
  it ('should successfully handle fetchMovies', () => {
    var callback = sinon.spy();
    var date = {
      startDate: moment('2015-04-01').format('YYYY-MM-DD'),
      endDate: moment('2015-04-15').format('YYYY-MM-DD')
    };

    AppActions.fetchMovies(date, callback);

    requests[0].respond(200, { 'Content-Type': 'application/json' },
      '[{ "id": 12, "comment": "Hey there" }]');

    expect(callback.calledWith([{id: 12, comment: "Hey there"}])).to.be.ok;
  });

This obviously doesn't work because fetchMovies only takes one argument - date. It's my first time using sinon.js, so perhaps I am missing something really obvious?

How do I fake this asynchronous request and make it either succeed or fail, because right now no matter what I do, it never resolves the .end() promise.

1

There are 1 answers

1
Henrik Andersson On

You should use nock for this.

Nock intercepts all HTTP requests going from your code and then respons according to how you've set it up. This way you can keep your mocks and spys down to a minimum and treat request as just another implementation detail.

The nock scope you create responds to certain assertions, so you can expect that it was done, faulty or similar.

An example;

var nockScope = nock('http://localhost:8000').get('/api/movies').reply(200, 'OK')

expect(nockScope.isDone()).to.be.ok()