18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Sinon.JSのFakeServerでAjaxをテストする

Posted at

今更感漂うのだけど…… FakeServerを使ってAjax関連のテストを書く機会があまりないので、書いておかないと忘れてしまうのでメモを。

// jQuery + Mocha + expect.js + Sinon.JS

suite('API', function() {

  var server;

  beforeEach(function() {
    // 疑似サーバの生成
    server = sinon.fakeServer.create();
  });

  afterEach(function() {
    // スタブのXHRとかを戻す
    server.restore();
    server = null;
  });

  it('データが返ってくること', function(done) {
    var res = 200,
        head = {'Content-Type': 'application/json'},
        body = JSON.stringify({
          data: 'data'
        });

    // レスポンスの指定
    server.respondWith('POST', '/path/to/api', [
      res, head, body
    ]);

    // リクエスト
    $.post('/path/to/api', function(data, textStatus, jqXHR) {
      expect(JSON.parse(data).data).to.be('data');
      done();
    });

    // 疑似サーバからレスポンスを返す
    server.respond();
  });

});

確かこんな感じ。

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?