AngularJS $ httpBackend验证没有交互

时间:2016-03-25 15:35:34

标签: angularjs

我正在寻找评估$httpBackend以查看是否存在任何互动的方法。我想确保在我的测试用例中此时从未调用它。我在这里查看了文档:https://docs.angularjs.org/api/ngMock/service/ $ httpBackend并且没有找到答案。

使用$ http的类

class HomeService {
  /*@ngInject*/
  constructor ($http, $log) {
    this.http = $http;
    this.log = $log;
  }

  submit(keycode) {
    this.log.log("submitting key code: " + keycode);
    if (keycode === "") {
      return false;
    }
    this.http.post(`/api/keycode/${keycode}`).then ( (response) => {
      this.log.log(response);
      return true;
    });
  }
}

export default HomeService;

到目前为止的测试案例。

import HomeService from './home.service';

describe('HomeService', () => {
  let homeService, $httpBackend;

  beforeEach(inject(($injector) => {
    $httpBackend = $injector.get('$httpBackend');
  }));

  afterEach(function() {
   $httpBackend.verifyNoOutstandingExpectation();
   $httpBackend.verifyNoOutstandingRequest();
 });

  describe('submit', () => {

    it('submit empty keycode', () => {
      homeService = new HomeService($httpBackend, console);
      let value = homeService.submit("");
      expect(value).to.be.false;
      //valid no interactions with $httpBackend here!
    });
  });
});

1 个答案:

答案 0 :(得分:0)

即使

  afterEach(function() {
   $httpBackend.verifyNoOutstandingExpectation();
   $httpBackend.verifyNoOutstandingRequest();
 });

可能足以抛出不需要的请求,将错误与特定的规范使用联系起来:

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