【问题标题】:How to change $httpBackend when[method] statements between requests in unit testing?如何在单元测试中的请求之间更改 $httpBackend when[method] 语句?
【发布时间】:2014-08-08 19:30:11
【问题描述】:

在我的测试中,我启动了一些模型数据并模拟了响应:

beforeEach(function(){
   var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
   $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
});      

it('should find 5000 users in channel 12345', function(){
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000);
});

然后在下一个测试语句中说我想要通道的更新值。每个人都离开了,假设这会触发其他行为,所以我需要模拟第二个请求,以便测试该行为。

$httpBackend.whenGET 添加到下一个it 语句不会覆盖beforeEach 值。好像用的是原来的mock值:

it('should find 0 users in channel 12345', function(){
    $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

如果我在没有 beforeEach 的情况下这样做,两者都会因通常的“unexpectedGet”错误而失败。

it('should find 5000 users in channel 12345', function(){
     var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

it('should find 0 users in channel 12345', function(){
      var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 0); //fails
});

如何在请求之间调制模拟数据?

我也试过了:

  • beforeEach 夹在it 语句之间
  • .respond( 设置为fakeResponse 变量。然后更改每个it 语句中的fakeResponse 值。

【问题讨论】:

  • 我没有看到任何发出 http 请求的东西。您必须在发出请求之前设置$httpBackend

标签: javascript angularjs unit-testing jasmine


【解决方案1】:

resetExpectations()

执行

afterEach($httpBackend.resetExpectations);

文档

重置所有请求预期,但保留所有后端定义。通常,当您想重用 $httpBackend 模拟的同一实例时,您会在多阶段测试期间调用 resetExpectations。

文档来源:https://docs.angularjs.org/api/ngMock/service/$httpBackend

【讨论】:

  • 啊,我曾经尝试过这个,然后我意识到我需要使用 expect('GET',regex).respond() 而不是 whenGET(...)
  • 实际上,我欺骗自己认为这有效。我仍然没有运气。既然我对这个问题有了更多的了解,我就用一个示例 jsFiddle 提出了一个新问题:stackoverflow.com/questions/25370273/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多