gpt4 book ai didi

在 rails 中测试 angular.service

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

我正在尝试使用 jasmine 测试我的服务,但我一直在尝试“Unknown provider: AuthServiceProvider <- AuthService in angular/angular.js on line 2683”

我的服务定义:

app.factory( 'AuthService', ["$resource", "$rootScope", "apiPrefix", function($resource, $rootScope,  apiPrefix) {
auth_resource = $resource(apiPrefix + "/session", {}, {
logout: {method:'GET'}
});

var currentUser;
return {
login: function(email, password, success, failure) {
auth_resource.save({}, {
email: email,
password: password
}, function(response){
currentUser = response
success()
}, function(response){
failure()
});
},
logout: function(success, failure) {
auth_resource.logout(
function(response){
currentUser = undefined
}, function(){
$scope.alerts.push({type: "success", msg: "Logged out" })
}, function(){
$scope.alerts.push({type: "error", msg: "Sorry, something went wrong" })
}
)
},
isLoggedIn: function(){ return currentUser !== undefined},
currentUser: function() { return currentUser; }
};
}]);

和我的测试:

describe("AuthService", function(){
var httpBackend;
beforeEach(inject(function($httpBackend, AuthService){
module('app');

httpBackend = $httpBackend;
AService = AuthService;
}));


it("should login the user", function(){
// test here
});
});

我的 jasmine 配置文件是:

// This pulls in all your specs from the javascripts directory into Jasmine:
// spec/javascripts/*_spec.js.coffee
// spec/javascripts/*_spec.js
// spec/javascripts/*_spec.js.erb

//= require application
//= require_tree ./

这似乎配置正确,因为我可以很好地测试我的 Controller ,所以我不确定为什么它不能识别我的服务。

最佳答案

可以使用$injector获取服务,然后像这样注入(inject)到实际测试中

describe("AuthService", function () {
var httpBackend, AService, apiPrefix;
beforeEach(module('app'));

beforeEach(function () {
angular.mock.inject(function ($injector) {
httpBackend = $injector.get('$httpBackend');

apiPrefix = angular.mock.module('apiPrefix'); // I assume you have apiPrefix module defined somewhere in your code.
AService = $injector.get('AuthService', {apiPrefix: apiPrefix});
})
});

it("should login the user", inject(function (AService) {
// test here
}));
});

我假设您在代码中某处定义了 apiPrefix 模块。

关于在 rails 中测试 angular.service ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18454937/

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