我尝试为 Angular 服务中的 post 方法编写一个单元测试用例。我收到 $http 未定义错误。下面是我的代码。任何人都可以告诉我我错过了什么。 我正在使用单独的文件添加模块。 服务代码
sample.factory('AddProductTypeService', function () {
return {
exciteText: function (msg) {
return msg + '!!!'
},
saveProductType: function (productType) {
var result = $http({
url: "/Home/AddProductTypes",
method: "POST",
data: { productType: productType }
}).then(function (res) {
return res;
});
return result;
}
};
});
Jasmine
describe("AddProductTypeService UnitTests", function () {
var $rootScope, $scope, $factory, $httpBackend, basicService,createController, authRequestHandler;
beforeEach(function () {
module('sampleApp');
inject(function ($injector) {
basicService = $injector.get('AddProductTypeService');
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
});
});
// check to see if it does what it's supposed to do.
it('should make text exciting', function () {
var result = basicService.exciteText('bar');
expect(result).toEqual('bar!!!');
});
it('should invoke service with right paramaeters', function () {
$httpBackend.expectPOST('Home/AddProductTypes', {
"productType": "testUser"
}).respond({});
basicService.saveProductType('productType');
$httpBackend.flush();
});
});
错误:
引用错误:$http 未定义
提前致谢
最佳答案
您必须将 $http
服务注入(inject)您的服务
sample.factory('AddProductTypeService', ['$http' ,function ($http) {
/* ... */
}]);
关于javascript - 使用 Jasmine 进行 http post 方法的单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31284535/