在服务单元测试中修复意外的GET请求

时间:2015-07-27 15:38:19

标签: angularjs unit-testing jasmine angular-services

在我的服务单元测试中,我正在测试GET请求。即使我明确说明$httpBackend.expectGET('/api/example').respond(200, {});

,我也会收到以下错误
Error: Unexpected request: GET /api/another/example
Expected GET /api/example

单元测试

 describe('MyService', function() {
    var MyService,
        $httpBackend;

    beforeEach(module('example'));

    beforeEach(function() {
      inject(function(_MyService_, _$httpBackend_) {
        MyService = _MyService_;
        $httpBackend = _$httpBackend_;

        $httpBackend.expectGET('/api/example').respond(200, {});
      });
    })

    describe('#get', function() {
      beforeEach(function() {

        // this is what i want to test
        $httpBackend
          .expectGET('/api/another/example')
          .respond(200, {});

      });

      it('should send a get request', function() {
        MyService.get();

        $httpBackend.flush();
      });
    });

  });

1 个答案:

答案 0 :(得分:0)

我无法看到您MyService.get()函数的内容,但我会继续并假设它正在调用GET /api/another/example

如果我没记错的话,您必须按照您列出的顺序在$httpBackend上提供预期的请求。

假设在触发每个段之前,您必须先针对GET启动/api/example请求,然后才能访问GET /api/another/example

相关问题