【问题标题】:AngularJS Jasmine Unit TestsAngularJS Jasmine 单元测试
【发布时间】:2013-08-29 23:43:37
【问题描述】:

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

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

【问题讨论】:

  • 你遇到了什么错误?没有它,没人能猜到。
  • 当然!多么可怕的错误。现在更新错误...
  • 尝试提高 Karma 的日志级别进行调试,看看会发生什么。
  • 仅仅因为你在 .flush() 中看到一个错误并不意味着它就是问题所在。那么 deleteEpicResource() 呢?你的测试设置呢?其他浏览器也会出现这种情况吗?
  • 尝试改用 whenGET、whenDELETE、whenWHATEVER 方法,这可能会奏效。如果你使用 angular-unstable,你可能想调用 rootScope.$digest() (不知道为什么,但它解决了我的一些问题......)

标签: javascript unit-testing testing angularjs jasmine


【解决方案1】:

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

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

尝试在调用httpBackend.flush() 之前运行scope.$digest(),这可能会奏效。请参阅this thread 了解更多信息。

【讨论】:

  • 我不久前修复了这个问题,但不记得我是如何修复它的。在阅读您的回复后,我意识到我并没有为我需要的所有请求调用 flush()。这主要是个问题,因为我的控制器一加载就加载了 API 请求,但我忘记了它们。
  • 添加 $digest() 是否解决了 Chrome 崩溃的问题?
【解决方案2】:

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

beforeEach(module("ngMock"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多