我有以下单元测试,由于某种原因,第二次测试使其他测试失败。
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()
行。为什么flush函数会导致奇怪的行为?
在终端中运行命令karma start
时得到的实际错误是:
Delaying execution, these browsers are not ready: Chrome 29.0 ....
过了一会儿,Chrome会话就崩溃了。
答案 0 :(得分:2)
关于使用jasmine和AngularJS测试/模拟异步请求的一个鲜为人知的提示:
如果你没有在你的测试中明确地调用请求(即通过另一个函数调用它),那么Angular不会消化请求,所以它看起来好像请求永远不会被触发(当你调用{ {1}})
尝试在flush()
来电之前运行scope.$digest()
,这可能会有所帮助。有关详细信息,请参阅this thread。
答案 1 :(得分:0)
在测试之前是否包含angular-mocks.js?此外,您可能想尝试加载ngMocks模块:
beforeEach(module("ngMock"));