Angularjs 使用配置参数模拟$http

Angularjs 使用配置参数模拟$http,angularjs,unit-testing,http,karma-jasmine,httpbackend,Angularjs,Unit Testing,Http,Karma Jasmine,Httpbackend,我在一个现有的AngularJS应用程序中应用了一些测试,以确保它在代码的未来更改中的正确行为 我对Jasmine&Karma测试还很陌生,所以我决定从一个小型的基本服务开始,它向后端执行一个http请求,并承诺等待结果,没有什么新的 以下是要测试的服务方法: function getInformedConsent(queryParameters) { var def = $q.defer(), httpParameters = { url: EN

我在一个现有的AngularJS应用程序中应用了一些测试,以确保它在代码的未来更改中的正确行为

我对Jasmine&Karma测试还很陌生,所以我决定从一个小型的基本服务开始,它向后端执行一个http请求,并承诺等待结果,没有什么新的

以下是要测试的服务方法:

function getInformedConsent(queryParameters) {
    var def = $q.defer(),
        httpParameters = {
            url: ENV.apiEndpoint + '/urlResource',
            method: 'GET',
            params: queryParameters,
            paramSerializer: '$httpParamSerializerJQLike'
        };

    $http(httpParameters)
        .then(
            function (response) {
                def.resolve(response);
            },
            function (error) {
                def.reject(error);
            }
        );

    return def.promise;
}
这是我的测试:

it('getInformedConsent method test', function() {
    $httpBackend.expectGET(/.*\/urlResource?.*/g)
        .respond(informedConsentJson.response);

    var promise;

    promise = InformedconsentService.getInformedConsent(informedConsentJson.queryParameters[0]);
    promise
        .then(function(response) {
            console.log(response);
            expect(response).toEqual(informedConsentJson.response);
        });

    $httpBackend.flush();

});
InformedJSON是一个包含输入和预期输出的装置

在阅读AngularJS文档时,我决定使用$httpBackend,因为它已经是$http服务的仿制品,所以我认为它可能很有用

问题是代码中的某个地方,有人正在广播“$locationChangeStart”事件并执行

$rootScope.$on('$locationChangeStart', function (event,current,old) {
    /* some code here */
});
在app.js中

我不是想改变URL,我只是想从模拟的后端获取一些数据

我估计这是因为我没有使用应该使用的$HTTPMock($httpBackend)

有人能帮我配置JSON模拟的$http吗? 这把我吓坏了


提前感谢您的时间和回复

旁注:在
getInformedApprovement
上,您可以简单地
返回$http(httpParameters)
,而不是使用仅包装原始承诺的延迟@莱昂纳多奇亚非常有趣的帖子。非常感谢。嘿@wrrzag,没问题。也许你可以编辑你的问题来解释你的实际问题。希望这些变化将有助于理解问题。