gpt4 book ai didi

javascript - Angular 测试 http 请求报错

转载 作者:行者123 更新时间:2023-11-30 16:54:28 24 4
gpt4 key购买 nike

我正在尝试使用动态 url 测试 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

我不确定如何测试动态 url。谁能帮我解决这个问题?非常感谢!

最佳答案

您的代码中没有设置 id,因此 url 变为:

/api/product//description

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

那么,为什么没有定义 id?在您设置的位置显示代码。

在测试“动态”网址时,您需要设置您的测试,以便您知道 id 的值是什么,并期望它。无法预期 url 的模式。

您可以通过更改描述 block 的第一行来修改 cookie 的值:

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

现在您可以预期,当 URL 调用发生时,id 将为 3。

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

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

关于javascript - Angular 测试 http 请求报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29956548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com