gpt4 book ai didi

javascript - Angular 单元测试http请求问题

转载 作者:行者123 更新时间:2023-12-03 10:50:21 25 4
gpt4 key购买 nike

我正在尝试为我的 http 请求编写单元测试

在我的 Controller 中,我有类似的东西

     $scope.test1 = function(url) {
productFactory.getProduct(url)
.then(function(products){
$scope.result = products;
})
}

在我的单位工厂文件中

    angular.module('myApp').factory('productFactory', function($http) {
var factoryObj = {};
factoryObj.getProduct = function(url) {
return http.get('/product/' + url)
}
return factoryObj
})

在我的单元测试中,我不确定如何编写测试,因为 url 是动态的

describe('test here', function () {
var testCtrl, scope, httpBackend, mockFactory;

// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _productFactory_) {
scope = _$rootScope_.$new();
httpBackend = _$httpBackend_;
mockFactory = _productFactory_;

testCtrl = _$controller_('testCtrl', {
$scope: scope
});


// the url is dynamic so I am not sure what to write here.

var url = 12345 <----dynamic product id
httpBackend.whenGet('/product/' + url).response({'name':'product1'})
var promise = mockFactory.getProduct('/product/' + url);
promise.then(function (prod) {
var products = prod;
});
$httpBackend.flush();
expect(products).toBeTruthy();
}));

当我运行测试时,我得到了

Error: Unexpected request: GET /product/undefined
Expected GET /product/12345

我不知道如何在我的情况下编写 http 请求。谁能帮我解决这个问题吗?谢谢!

最佳答案

您似乎想要测试 productFactory 而不是 Controller 。我能看到的唯一测试是确保发出适当的 HTTP 请求。

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

it('getProduct requests /product/:id', inject(function($httpBackend, productFactory) {
var id = 123;
$httpBackend.expectGET('/product/' + id);

productFactory.getProduct(id);
$httpBackend.flush();
}));
});

此外,productFactory.getProduct 中存在拼写错误。它应该是 $http.get,而不是 http.get

<小时/>

假设您的工厂使用cookie服务来获取ID。像这样的事情...

.factory('productFactory', function($http, cookieService) {
return {
getProduct: function() {
return $http.get('/product/' + cookieService.getProductid());
}
};
});

然后您将像这样测试它(假设 jasmine v2)...

describe('...', function() {
var cookieService;

beforeEach(module('myApp', function($provide) {
$provide.value('cookieService',
cookieService = jasmine.createSpyObj('cookieService', ['getProductId']));
});

it('...', inject(function($httpBackend, productFactory) {
cookieService.getProductId.and.returnValue(123);
$httpBackend.expectGET('/product/123');

productFactory.getProduct();
expect(cookieService.getProductId).toHaveBeenCalled();

$httpBackend.flush();
}));
});

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

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