角度测试http请求错误

时间:2015-04-29 23:41:42

标签: javascript angularjs unit-testing

我正在尝试使用动态网址测试http请求

我的服务文件中有一些内容,如

我的服务档案。

//other service codes..
//other service codes..
var id = $cookies.id;
return $http.get('/api/product/' + id + '/description')
//id is dynamic 

测试文件

describe('test', function () {
    beforeEach(module('myApp'));

    var $httpBackend, testCtrl, scope;

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
        scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        testCtrl = _$controller_('testCtrl', {
            $scope: scope
        });
    }));

    it('should check the request', function() {
        $httpBackend.expectGET('/api/product/12345/description').respond({name:'test'});
        $httpBackend.flush();
        expect(scope.product).toBeDefined();
    })
});

我收到错误说

Error: Unexpected request: GET /api/product/description

我不确定如何测试动态网址。任何人都可以帮我吗?非常感谢!

1 个答案:

答案 0 :(得分:2)

您的代码中没有设置ID,因此网址变为:

/api/product//description

减少到您在意外请求中看到的内容(// - > /)

那么,为什么不定义id?显示您设置的代码。

在测试“动态”网址时,您需要设置测试,以便了解id的值,并期望这样。没有办法预期网址模式。

您可以通过更改describe块的第一行来修改Cookie的值:

beforeEach(module('myApp', function($provide) {
  $provide.value('$cookies', {
    id: 3
  });
}));

现在,当URL调用发生时,你可以期望id为3。

虽然这很粗糙。你也可以在第二个beforeEach块中注入$ cookies并设置它

beforeEach(inject(function($cookies) {
    $cookies.put('id', 3);
}))