使用 Typescript 测试在 Karma 中注入服务

Inject Service in Karma with Typescript test

我在应用程序中进行测试时遇到了同样的问题。我开始使用 TypeScript,并且还在学习中。

我遇到了这个错误:

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);
      });
  }

}

我可以用这段代码注入控制器:

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

下面的注入工作正常。直接注入 MovieService。

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

但是当我使用 "it" 上的注入进行测试时,如下所示

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

他无法解决这一秒MovieService。如果我在 1 示例中使用 movieService 变量集。如下所示:

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

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