我对单元测试 javaScript、angularJS 和 Karma 完全是个菜鸟。我已经能够为控制器编写通过测试,但现在我正在尝试测试服务,我收到以下错误:Unknown provider <- nProvider <- User
其中 User 是我的服务的名称,据我所知,“n " 是该服务的 $http 依赖项(已缩小)。这是我的用户服务(TypeScript):
/// <reference path="../../lib/angular/angular.d.ts" />
module MyApp.Services{
export class UserService{
private _apiBase: string = "api/";
constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
}
getUser(userSearchParams: string): ng.IPromise{
var deferred = this.$q.defer();
this.$http.get(this._apiBase + "Users/" + userSearchParams).success((data) => {
deferred.resolve(data);
}).error(() => {
deferred.reject();
});
return deferred.promise;
}
}
}
这是我的通用 Services.ts 文件:
/// <reference path="../_all.d.ts" />
'use strict'
var mod = angular.module('MyApp.Services', []);
mod.factory('User', [<any>"$http", <any>"$q", function ($http, $q) {
return new MyApp.Services.UserService($http, $q);
}]);
最后,我的测试脚本:
'use strict';
describe('UserServiceTests', function () {
beforeEach(module('main')); //this is my main angular module - set up in app.ts
it('should issue a GET request to api/Users/whatever when the search parameter is whatever', inject(function(User) {
expect(2).toBe(2);
}));
})
我创建了另一个具有相同结构的测试应用程序,但没有收到上面看到的错误。我不知道我错过了什么。让我知道是否还有其他需要发布的内容才能找到问题。任何帮助表示赞赏。
Edit: After much searching and reading, it appears that this is related to dependency injection here and here. Upon minification, the parameter names get changed, thus causing the error. As proof, if I delete the min files and re-run the tests, they pass.
The $inject function can be used to fix this, but I don't see how to do it when the controller is created as a class using TypeScript. I'm not sure if I can use the resolve property of $routeProvider.when.