3

经过一番反复试验,我终于设法让 Jasmine 注入一个模拟 Angular 服务,并$httpBackend在同一个套件中提供:

describe('services.system', function () {

    var httpBackend, nodeService;

    beforeEach(module('services.system'));

    beforeEach(function() {
        module(function($provide) {
            $provide.factory('authService', function() { return mockAuthService; });
        });

        inject(function(_nodeService_, $httpBackend) {
            httpBackend = $httpBackend;
            nodeService = _nodeService_;
        });
    });

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    describe('version', function () {
        it('should return the current version', function () {
            httpBackend.expectGET('/service/version').respond(200, { version: "1.2.3"});

            var done = false;
            runs(function() {
                nodeService.getProductInfo().then(function (info) {
                    expect(info.version).toEqual('1.2.3');
                    done = true;
                }, function(error) {
                    expect("test received error: " + error).toFail();
                    done = true;
                });

                httpBackend.flush();
            });

            waitsFor(function(){
                return done;
            });
        });
    });
});

我现在想编写一个只需要一次 GET 的测试,两个连续的调用应该返回一个缓存的响应,而不是向服务器发出另一个请求。对于间谍,您通常可以通过断言来做到这一点myObj.calls.count()

如何验证 HTTP 请求只被调用过一次?

4

0 回答 0