27

是否可以在模拟的 $httpBackend 中覆盖或重新定义模拟响应?

我有这样的测试:

beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
  $httpBackend = _$httpBackend_;

  //Fake Backend
  $httpBackend.when('GET', '/myUrl').respond({}); //Empty data from server
  ...some more fake url responses...     
 }

这在大多数情况下都很好,但我很少有测试需要为同一个 URL 返回不同的东西。但似乎一旦定义了 when().respond() 之后,我就无法在这样的代码中更改它:

单个特定测试中的不同响应:

it('should work', inject(function($controller){
  $httpBackend.when('GET', '/myUrl').respond({'some':'very different value with long text'})

  //Create controller

  //Call the url

  //expect that {'some':'very different value with long text'} is returned
  //but instead I get the response defined in beforeEach
}));

我怎么做?我的代码现在无法测试:(

4

5 回答 5

28

文档似乎建议这种风格:

var myGet;
beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
    $httpBackend = $_httpBackend_;
    myGet = $httpBackend.whenGET('/myUrl');
    myGet.respond({});
});

...

it('should work', function() {
    myGet.respond({foo: 'bar'});
    $httpBackend.flush();
    //now your response to '/myUrl' is {foo: 'bar'}
});
于 2014-08-12T07:29:40.133 回答
12

在响应中使用函数,例如:

var myUrlResult = {};

beforeEach(function() {
  $httpBackend.when('GET', '/myUrl').respond(function() {
    return [200, myUrlResult, {}];
  });
});

// Your test code here.

describe('another test', function() {
  beforeEach(function() {
    myUrlResult = {'some':'very different value'};
  });

  // A different test here.

});
于 2014-05-14T16:08:58.067 回答
9

另一种选择是:

您可以使用 $httpBackend.expect().respond()而不是$httpBackend.when().respond()

使用expect(),您可以将相同的 url 推送两次,并以推送它们的相同顺序获得不同的响应。

于 2015-02-06T10:25:45.630 回答
6

在您的测试中使用 .expect() 而不是 .when()

var myUrlResult = {};

beforeEach(function() {
  $httpBackend.when('GET', '/myUrl')
      .respond([200, myUrlResult, {}]);
});


it("overrides the GET" function() {
  $httpBackend.expect("GET", '/myUrl')
      .respond([something else]);
  // Your test code here.
});
于 2015-04-20T21:05:36.710 回答
0

您可以在进行测试的同一功能中重置“何时”响应。

it('should work', inject(function($controller){
    $httpBackend.when('GET', '/myUrl').respond({'some':'value'})
    // create the controller
    // call the url
    $httpBackend.flush();
    expect(data.some).toEqual('value');
});
it('should also work', inject(function($controller){
    $httpBackend.when('GET', '/myUrl').respond({'some':'very different value'})
    // create the controller
    // call the url
    $httpBackend.flush();
    expect(data.some).toEqual('very different value');
});

请参阅此 plunker 中的示例:http ://plnkr.co/edit/7oFQvQLIQFGAG1AEU1MU?p=preview

于 2013-08-28T19:36:25.377 回答