Ajax のモック化

ajax 呼び出しのテスト

jasmine-ajax というプラグインを作成しました。これを使用すると、Ajax 呼び出しをテストでモックアウトすることができます。使用するには、mock-ajax.js ファイルをダウンロードして Jasmine ヘルパーに追加する必要があります。これにより、使用する仕様の前にファイルがロードされます。

describe("mocking ajax", function() {

スイート全体における基本的な使用法

    describe("suite wide usage", function() {

スイート全体で Ajax 呼び出しをすべてモックアウトするには、beforeEachinstall() を使用します。

        beforeEach(function() {
            jasmine.Ajax.install();
        });

jasmine-ajax がページのグローバル XMLHttpRequest をスタブ化するので、実際の ajax 要求を作成すると予想される仕様やセットアップができるように、afterEachuninstall() が必要になります。

        afterEach(function() {
            jasmine.Ajax.uninstall();
        });

        it("specifying response when you need it", function() {
            const doneFn = jasmine.createSpy("success");

いつもどおりリクエストを作成します。Jasmine-Ajax は XMLHttpRequest オブジェクトでリクエストをモックアウトします。そのため、ajax 要求を実行する他のライブラリとも互換性があるはずです。

            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(args) {
                if (this.readyState == this.DONE) {
                    doneFn(this.responseText);
                }
            };

            xhr.open("GET", "/some/cool/url");
            xhr.send();

ここではまだ ajax 要求は返されません。そのため、中間状態(スピナーなど)に関する主張を実行できます。

            expect(jasmine.Ajax.requests.mostRecent().url)
                .toBe('/some/cool/url');
            expect(doneFn).not.toHaveBeenCalled();

ここで要求に予想される応答を指示します。

            jasmine.Ajax.requests.mostRecent().respondWith({

HTTP 応答コード

                "status": 200,

応答のコンテンツ タイプも指定できます。

                "contentType": 'text/plain',

返す responseText。これは文字列である必要があります。

                "responseText": 'awesome response'
            });

これで要求に応答するように指示を出したので、コールバックが呼び出されます。

            expect(doneFn).toHaveBeenCalledWith('awesome response');
        });

事前に応答を指定することもできます。そうすると、リクエストが行われるとすぐに応答します。

        it("allows responses to be setup ahead of time", function () {
            const doneFn = jasmine.createSpy("success");

直ちに応答させる URL を指定して stubRequest を呼び出します。次に、andReturnrespondWith と同じタイプの引数を受け取ります。

            jasmine.Ajax.stubRequest('/another/url').andReturn({
                "responseText": 'immediate response'
            });

いつもどおりリクエストを作成します。

            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(args) {
                if (this.readyState == this.DONE) {
                    doneFn(this.responseText);
                }
            };

            xhr.open("GET", "/another/url");
            xhr.send();

            expect(doneFn).toHaveBeenCalledWith('immediate response');
        });
    });

1 つの仕様だけで使用したい場合は、withMock を使用できます。withMock は、ajax がモックされた後に呼び出される関数を取得し、関数が完了するとモックはアンインストールされます。

    it("allows use in a single spec", function() {
        const doneFn = jasmine.createSpy('success');
        jasmine.Ajax.withMock(function() {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(args) {
                if (this.readyState == this.DONE) {
                    doneFn(this.responseText);
                }
            };

            xhr.open("GET", "/some/cool/url");
            xhr.send();

            expect(doneFn).not.toHaveBeenCalled();

            jasmine.Ajax.requests.mostRecent().respondWith({
                "status": 200,
                "responseText": 'in spec response'
            });
    
            expect(doneFn).toHaveBeenCalledWith('in spec response');
        });
    });
});