Fabio Picheli
Fabio Picheli

Reputation: 959

Inject Service in Karma with Typescript test

I'm having same problem with make the test in my application. I started to use TypeScript and I still learning.

I'm facing this error:

Error: [$injector:unpr] Unknown provider: movieProvider <- movie

movie.spec.ts

import { MovieService } from './movie';

describe('service MovieService', () => {
  let movieService: MovieService;

  beforeEach(angular.mock.module('movieSearch'));

  it('should be registered', inject((movie : MovieService) => {
    expect(movie).not.toBeNull();
  }));
});

movie.ts

/** @ngInject */
export class MovieService {
  static $inject = ['$log', '$http', 'LoaderManager'];
  public apiMovieDetail: string = 'http://www.omdbapi.com/';

  /** @ngInject */
  constructor(private $log: angular.ILogService, private $http: angular.IHttpService, private loader: LoaderManager) {
  }

  public getMovie(id: string): angular.IPromise<IMovie> {
    this.loader.add();
    return this.$http.get(this.apiMovieDetail + '?plot=short&r=json&i=' + id).then((response: any): any => {
        this.loader.remove();
        return response.data;
      })
      .catch((error: any): any => {
        this.loader.remove();
        this.$log.error('XHR Failed for getMovie.\n', error.data);
      });
  }

}

I'm able to inject the controller with this code:

beforeEach(inject(($controller: angular.IControllerService) => {
    mainController = $controller('MainController');
}));

Upvotes: 0

Views: 1708

Answers (1)

Fabio Picheli
Fabio Picheli

Reputation: 959

The below injection was working. Injecting direcly the MovieService.

  beforeEach(inject((MovieService: MovieService, $httpBackend: angular.IHttpBackendService, $log: angular.ILogService) => {
    movieService = MovieService;
    httpBackend = $httpBackend;
    log = $log;
  }));

But when I make the test using the injection on "it" like below

  it('should be registered', inject((movie : MovieService) => {
    expect(movie).not.toBeNull();
  }));

He cannot resolve this second MovieService. If I use the movieService variable set on the 1 example works. Like below:

beforeEach(inject((movieService: MovieService) => {
    movieService = $httpBackend;
}));

it('should be registered', inject(() => {
    expect(movieService).not.toBeNull();
}));

Upvotes: 2

Related Questions