[英]How to create unit test for http request in my case
I am trying to create a unit test for a random generate url. 我正在尝试为随机生成的URL创建单元测试。
My item Controller JS 我的项目Controller JS
init()
function init(){
var results = itemService.request();
other codes..
}
My itemService js 我的itemService js
function request(){
other codes..
return $http.get(url);
}
function generateUrl() {
var url = 'https://project/'
var num = Math.floor((Math.random() * 100) + 1);
url += num;
other codes to generate more attribute for url…
return url
}
Unit test: 单元测试:
beforeEach(function () {
module(‘itemApp’);
inject(function ($injector) {
$controller = $injector.get('$controller');
itemService = $injector.get(‘itemService’);
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
$httpBackend = $injector.get('$httpBackend');
});
vm.$controller(‘itemCtrl’, {
‘$scope’:$scope
})
$httpBackend.when('GET', 'https://project/15/other-attributes').respond(200);
});
describe('initialization', function() {
it(‘start init’ , function(){
//not sure what to do.
});
The application works but I am getting 该应用程序有效,但我正在
Error: Unexpected request: GET https://project/12/other-attributes
when I ran the unit test because I will have random numbers in my url. 当我运行单元测试时,因为我的URL中将包含随机数。
I am not sure how to mock the url because it generates randomly. 我不确定如何模拟网址,因为它是随机生成的。 Can anyone help me about it? 有人可以帮我吗? Thanks a lot! 非常感谢!
Have you tried something like this, 你有没有尝试过这样的事情,
$httpBackend.when('GET', /https:\/\/project\/[0-9]+\/other-attributes/).respond(200);
$httpBackend.when() method does support regex. $ httpBackend.when()方法确实支持正则表达式。
In case of dynamic environment variables, 如果是动态环境变量,
var environmentUrl = "http://google.com";
$httpBackend.when('GET', new RegExp(environmentUrl + '/[0-9]+/other-attributes')).respond(200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.