jeudi 4 juin 2015

How to use Sinon.js FakeXMLHttpRequest with superagent?

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.

Aucun commentaire:

Enregistrer un commentaire