5

我有以下单元测试,由于某种原因,第二个测试使其他测试失败。

beforeEach(inject(function ($rootScope, _$httpBackend_, $controller, $location, mockedResource) {
    scope = $rootScope.$new();
    httpBackend = _$httpBackend_;
    locationService = $location;

    ctrlDependencies = {
        $scope: scope, 
        resource: mockedResource,
    }

    var ctrl = $controller('myController', ctrlDependencies);
}));

it('should redirect to a new page', function() {
    scope.pageRedirectFunction();
    expect(locationService.path()).toBe('/newpage')
});

it('should delete an epic resource', function() {
    httpBackend.expectGET('/api/v1/epic/1').respond({});
    httpBackend.expectDELETE('/api/v1/epic/1').respond({});

    // Run the deletion function
    scope.deleteEpicResource()

    httpBackend.flush() // This line seems to be the rebelious one

    expect(scope.epicResources.length).toEqual(0)
})

我已经设法找出似乎导致错误的线,这就是httpBackend.flush()线。为什么刷新功能会导致奇怪的行为?

karma start我在终端中运行命令得到的实际错误是:

 Delaying execution, these browsers are not ready: Chrome 29.0 ....

过了一会儿,Chrome 会话然后崩溃。

4

2 回答 2

2

关于使用 jasmine 和 AngularJS 测试/模拟异步请求的鲜为人知的技巧:

如果您没有在测试中显式调用请求(即通过另一个函数调用它),则 Angular 不会消化该请求,因此看起来好像该请求从未触发(当您调用时flush()

scope.$digest()在你打电话之前尝试跑步httpBackend.flush(),这可能会奏效。有关更多信息,请参阅此线程

于 2013-09-04T17:07:06.723 回答
0

测试前是否包含 angular-mocks.js?此外,您可能想尝试加载 ngMocks 模块:

beforeEach(module("ngMock"));
于 2013-09-03T09:21:02.257 回答