【问题标题】:Angular JS Unit Testing $httpBackend spec has no expectationsAngular JS 单元测试 $httpBackend 规范没有期望
【发布时间】:2014-11-19 11:55:30
【问题描述】:

我有一个单元测试,其中唯一的期望是进行了 http 调用。我为此使用 $httpBackend.expect() 。这很好用,如果没有发出这个 http 请求,单元测试就会失败(这很好),如果发出了这个 http 请求,则单元测试通过。

问题在于,即使它通过了,Jasmine 规范运行程序也会在此单元测试中显示“规范没有期望”,这让我觉得我没有使用推荐的方法来测试是否进行了 http 调用。如何避免看到此消息?

示例测试:

it('should call sessioncheck api', function () {
    inject(function ($injector, SessionTrackerService) {
        $httpBackend = $injector.get('$httpBackend');

        var mockResponse = { IsAuthenticated: true, secondsRemaining: 100 };
        $httpBackend.expect('GET', 'API/authentication/sessioncheck')
            .respond(200, mockResponse);

        SessionTrackerService.Start();

        jasmine.clock().tick(30001);
        $httpBackend.flush();
    });
});

【问题讨论】:

  • 可以在此处添加您的代码只是为了说明一下吗?这可能是其他地方的一些小错误
  • 已添加到问题中。谢谢。
  • 我试图在这里重现这种情况:plnkr.co/edit/aGbBudhd3hYGa98g4V12?p=preview。但我没有收到那个警告,你能检查一下差异吗?
  • 我也有同样的问题。作为一个(非常丑陋的)解决方法,我在每个测试中添加 expect(true).toBeTruthy() 只是为了删除这个警告。
  • 我正在使用一些不那么难看的东西:expect('Suppress SPEC HAS NO EXPECTATIONS').toBeDefined();

标签: angularjs unit-testing jasmine


【解决方案1】:

我将flush的调用包装如下:

expect($httpBackend.flush).not.toThrow();

我更喜欢这种方法,因为测试代码清楚地说明了调用 flush 时“应该”发生什么。例如:

it('should call expected url', inject(function($http) {
    // arrange
    $httpBackend.expectGET('http://localhost/1').respond(200);

    // act
    $http.get('http://localhost/1');

    // assert
    expect($httpBackend.flush).not.toThrow();

}));

【讨论】:

    【解决方案2】:

    尝试删除 jasmine.clock().tick(30001);

    如果您在 SessionTrackerService.Start 方法中没有超时,则此代码过多

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 2020-10-26
      • 1970-01-01
      • 2017-06-28
      • 2021-05-09
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      相关资源
      最近更新 更多