$ http调用后再调用$ http调用返回单元测试

时间:2017-01-09 08:28:45

标签: javascript angularjs unit-testing jasmine

我有一段代码如下

function init() {
        $http({
            method: 'GET',
            url: baseUrl + 'service/'+'/serviceA',
            headers: {
                'Content-Type': "application/json",
            }
        }).then(function successResponse(response) {
            $scope.result = response.data;
            if ($scope.result) {
                // initB is another $http get method
                initB();
            }
          // initC is another $http get method
            initC();
          // initD is another $http get method
            initD();
        });
    }

我的单元测试如下

describe('Controller: toolbarCtrl', function() {
beforeEach(module('TestApp'));

var $httpBackend, $rootScope, createController,$location;

beforeEach(inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');
    $rootScope = $injector.get('$rootScope');
    $location = $injector.get('$location');
    var $controller = $injector.get('$controller');

    createController = function() {
        return $controller('toolbarCtrl', {
            '$scope': $rootScope
        });
    };       
}));

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

it("init B", function() {    
        $httpBackend.whenGET(/http:\/\/.*\/serviceA.*/).respond(200, true);
        $httpBackend.whenGET(/http:\/\/.*\/serviceB.*/).respond(200, ["A","B","C"]);
        var controller = createController();
        $httpBackend.flush();
        expect($rootScope.B).toBe(["A", "B", "C"]);
    });

但它不起作用,它会抛出异常

  

不满意的请求:GET / http://。 / serviceB。 /

如果我删除此行$httpBackend.whenGET(/http:\/\/.*\/serviceB.*/).respond(200, ["A","B","C"]);

代码不会抛出任何异常,但B不会被引入;

如果我删除$httpBackend.whenGET(/http:\/\/.*\/serviceA.*/).respond(200, true);

它会抛出异常:

  

意外请求:获取http://localhost:8633/serviceA

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

我无法看到你的测试中“it”函数之前的代码是什么,但看起来你没有实例化 $ httpBackend (或者在你实例化你的实例化之后可能会实例化它服务/控制器)。您的测试需要在您尝试测试的组件之前调用 $ httpBackend