Подтвердить что ты не робот

Как переопределить отклик $httpBackend в Angular?

Можно ли переопределить или переопределить отклик в mockinged $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-адреса. Но кажется, что после того, как определено значение if(). Response(), я не могу изменить его впоследствии в коде следующим образом:

Различные ответы в одном конкретном тесте:

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
}));

Как мне это сделать? Мой код теперь не тестируемый: (

4b9b3361

Ответ 1

Документы, кажется, предлагают этот стиль:

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'}
});

Ответ 2

Используйте функцию в ответе, например:

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.

});

Ответ 3

Еще один вариант:

Вы можете использовать $httpBackend.expect().respond() вместо $httpBackend.when().respond()

Используя expect(), вы можете дважды нажать один и тот же URL-адрес и получить разные ответы в том же порядке, который вы их нажали.

Ответ 4

В вашем тесте используйте .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.
});

Ответ 5

Вы можете reset "когда" ответы в той же функции, где вы проводите тесты.

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