2013-08-27 160 views
5

我有以下单元测试,由于某些原因,第二个测试使其他测试失败。AngularJS茉莉花单元测试

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会话然后崩溃。

+0

你有什么错误?没有人可以猜测。 – zsong

+0

当然!多么可怕的错误。现在更新错误... – Sneaksta

+0

尝试增加Karma的日志级别进行调试,看看会发生什么。 – madhead

回答

2

一个鲜为人知的尖端有关测试/嘲讽与茉莉异步请求和AngularJS:

如果你没有明确调用请求您测试(即通过另一个函数调用它),请求将不会被消化角,所以使得它看起来好像请求从未被触发(当你调用flush()

试试你的httpBackend.flush()调用之前运行scope.$digest(),即可能会诀窍。有关更多信息,请参阅this thread

+0

我修复了这一段时间,但不记得我是如何修复它。在阅读您的回复后,我意识到我没有为所有需要的请求调用flush()。这主要是一个问题,因为一旦我的控制器被加载,就有API请求被加载,但我忘记了它们。 – Sneaksta

+0

添加$ digest()是否解决了关于Chrome崩溃的问题? – kfitzpatrick

0

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

beforeEach(module("ngMock"));