angular 单元测试 $httpBackend 收到意外请求

angular unit test $httpBackend got Unexpected request

这是我的代码:

export class httpService {

constructor($q, $http){
    this.$q = $q;
    this.$http = $http;
}

static getError(response) {
    if (response.data && response.data.messages) {
        return response.data.messages;
    } else {
        return ["Sorry, there is an internal issue..."];
    }
}

httpRequest(url, method, data) {
    url = encodeURI(url);
    var deferred = this.$q.defer();
    this.$http({
        method: method,
        url: url,
        data: data
    }).then(function (response) {
        deferred.resolve(response.data);
    }, function (response) {
        deferred.reject(httpService.getError(response));
    });
    return deferred.promise;
}

}

我的测试代码:

import angular from 'angular';
import ngMock from 'angular-mocks';
import {httpService as HttpService} from '../http.service';

describe("httpService", ()=>{
    var httpService;
    var $q;
    var $timeout;
    var $httpBackend;
    var campaignHttpRequestHandler;
    var campaignTestUrl = 'api/campaign/aGJhZ2ZmZ2RmcmZ0';
    var campaignData = {
        "articles": [
            {
                "id": "1207",
                "type": "a",
                "order": 1
            },
            {
                "id": "940",
                "type": "p",
                "order": 2
            },
            {
                "id": "1268",
                "type": "a",
                "order": 3
            },
            {
                "id": "954",
                "type": "p",
                "order": 4
            }
        ],
        "year_month": "201606",
    };

    beforeEach(inject((_$q_, _$timeout_, _$httpBackend_)=>{
        $q = _$q_;
        $timeout = _$timeout_;
        $httpBackend = _$httpBackend_;
        campaignHttpRequestHandler = $httpBackend.when('Get', campaignTestUrl).respond(campaignData);

    }));

    beforeEach(()=>{
        httpService = new HttpService($q, $httpBackend);
    });

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

    describe("#httpRequest()", ()=>{

        it('should get campaign data', ()=>{
            $httpBackend.expect('Get', campaignTestUrl);

            httpService.httpRequest(campaignTestUrl, 'Get').then(
                (response)=>{
                    expect(response).toEqual(campaignData);
                }
            );

            $httpBackend.flush();


        });


    });





});

错误:

#httpRequest()
      ✖ should get campaign data
        Chrome 51.0.2704 (Mac OS X 10.11.5)
      Error: Unexpected request: [object Object] undefined

而且我调试到源码里面,$http已经被$httpBackend代替了。 不知何故,$httpBackend:method的第一个参数,是一个包含了method,url,data,和$http一样的请求参数的对象。显然,这是错误的。但是不知道怎么解决~

请帮忙。 卡在这里一整天了~

您应该传递 $http 而不是 $httpBackend 作为构造函数参数。

在您的测试代码中创建一个 $http 类型的变量并像这样传递它

beforeEach(()=>{
     httpService = new HttpService($q, $http)
});

一定会成功的。