簡體   English   中英

AngularJS茉莉花單元測試

[英]AngularJS Jasmine Unit Tests

我有以下單元測試,由於某種原因,第二次測試使其他測試失敗。

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會話就崩潰了。

關於使用jasmine和AngularJS測試/模擬異步請求的一個鮮為人知的提示:

如果你沒有在測試中顯式調用請求(即通過另一個函數調用它),Angular不會消化請求,所以它看起來好像請求永遠不會被觸發(當你調用flush()

嘗試在httpBackend.flush()調用之前運行scope.$digest() ,這可能會httpBackend.flush() 有關更多信息,請參閱此主題

在測試之前你是否包含angular-mocks.js? 此外,您可能想嘗試加載ngMocks模塊:

beforeEach(module("ngMock"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM