As a newcomer to unit testing in JavaScript, AngularJS, and Karma, I have successfully written passing tests for controllers. However, when trying to test services, I encountered an error:
Unknown provider <- nProvider <- User
. The User service is the one causing issues with its $http dependency being minified as "n". Below is my UserService code in 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;
}
}
}
Below is the generic Services.ts file:
/// <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);
}]);
Finally, here is my test script:
'use strict';
describe('UserServiceTests', function () {
beforeEach(module('main')); // Main Angular module defined 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);
}));
)I've set up another test app following the same structure without encountering the same error. I'm uncertain about what I might be missing. Please let me know if additional information is needed to pinpoint the issue. Any assistance would be greatly appreciated.
Edit: After extensive research, it seems that this problem is related to dependency injection here and here. Minification changes parameter names, leading to the error. Deleting the min files and rerunning the tests confirms they pass.
The $inject function can resolve this issue, but I am unsure how to implement it when using TypeScript to create a controller as a class. I am also not certain if I can utilize the resolve property of $routeProvider.when.