LoginSignup
3
4

More than 5 years have passed since last update.

sinon.jsのstubを使ったajaxテスト

Posted at

はじめに

jQueryのajaxを使う関数のUnit testでsinon.jsを使う場合、fakeServerを使うことが多いと思いますが、Stubを使って書く方法をメモ程度に残しておく。

書き方

テスト対象のコード

こんな感じのWeb APIの実行コードを想定する

var ajaxTest = {
    getHoge : function() {
        return $.ajax({
            type : 'GET',
            url : 'hoge',
            dataType : 'json',
            contentType : 'application/json; charset=UTF-8'
        });
    }
};

stubを使ってテスト

// JsTestDriver + sinon.js
TestCase('ajax test', {
    'testGetHoge' : function() {
        sinon.stub($, 'ajax').returns({
            done : function(cb) {
                cb('hoge');
            }
        });

        ajaxTest.getHoge().done(function(data) {
            assertEquals('hoge', data);
            $.ajax.restore();
        });
    }
});

ポイントは $.ajax を丸ごとStubで置き換えているところ。
ajaxが返すdone関数をMockしてやります。
一応これでカバレッジは100%になるので、わざわざfakeServerを作る必要はありません。

注意点としては、sinonで作ったstubは他のTest Suiteにも引き継がれてしまうので、ちゃんと restore() しておく必要があります。

ちなみにfakeServerを使うとこんな感じ

// JsTestDriver + sinon.js
TestCase('ajax test', sinon.testCase({
    'testGetHoge' : function(server) {
        this.server = sinon.fakeServer.create();

        ajaxTest.getHoge().done(function(data) {
            assertEquals('hoge', data);
        });

        this.server.requests[0].respond(200, {
            'content-type' : 'application/json'
        }, 'hoge');
    }
}));

あれ? fakeServerの方が簡単…?

3
4
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
3
4