Javascript测试框架Jasmine(六):异步代码测试
测试报告会自动追加到页尾
describe("mocking ajax", function() {
    describe("suite wide usage", function() {
        beforeEach(function() {
            jasmine.Ajax.install();
        });
        afterEach(function() {
            jasmine.Ajax.uninstall();
        });
        it("specifying response when you need it", function() {
            var doneFn = jasmine.createSpy("success");
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(arguments) {
                if (this.readyState == this.DONE) {
                    doneFn(this.responseText);
                }
            };
            xhr.open("GET", "/some/cool/url");
            xhr.send();
            expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
            expect(doneFn).not.toHaveBeenCalled();
            jasmine.Ajax.requests.mostRecent().response({
                "status": 200,
                "contentType": 'text/plain',
                "responseText": 'awesome response'
            });
            expect(doneFn).toHaveBeenCalledWith('awesome response');
        });
        it("allows responses to be setup ahead of time", function() {
            var doneFn = jasmine.createSpy("success");
            jasmine.Ajax.stubRequest('/another/url').andReturn({
                "responseText": 'immediate response'
            });
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(arguments) {
                if (this.readyState == this.DONE) {
                    doneFn(this.responseText);
                }
            };
            xhr.open("GET", "/another/url");
            xhr.send();
            expect(doneFn).toHaveBeenCalledWith('immediate response')
        });
    });
    it("allows use in a single spec", function() {
        var doneFn = jasmine.createSpy('success');
        jasmine.Ajax.withMock(function() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(arguments) {
                if (this.readyState == this.DONE) {
                    doneFn(this.responseText);
                }
            };
            xhr.open("GET", "/some/cool/url");
            xhr.send();
            expect(doneFn).not.toHaveBeenCalled();
            jasmine.Ajax.requests.mostRecent().response({
                "status": 200,
                "responseText": 'in spec response'
            });
            expect(doneFn).toHaveBeenCalledWith('in spec response');
        });
    });
});