无法在茉莉花单元测试中注入$资源

时间:2018-03-01 13:04:10

标签: angularjs typescript jasmine karma-jasmine jasmine2.0

我试图测试我编写的使用$ resource的服务,但在尝试将$ resource注入我的测试规范时遇到了问题。

我正在使用带有AngularJS 1.6.x的Typescript,我的服务类外观如下:

export class MyDataService {

  constructor(
    private $resource: ng.resource.IResourceService
    ) {
    this.someResource = $resource('api/some-endpoint');
  }

  public getThings() {
    return this.someResource.get().$promise;
  }
}

我的测试规范(使用Jasmine + Karma):

import { MyDataService } from './my-data-service.service';

describe('MyDataService Tests:', function() {
  let myDataService: MyDataService;
  let $resource: ng.resource.IResourceService;
  let resourceSpy: jasmine.Spy;

  beforeEach(inject(function(_$resource_){
    $resource = _$resource_;
    myDataService = new MyDataService($resource,);
    resourceSpy = spyOn(myDataService.resource, 'get');
  }));
  afterEach(function() {
    resourceSpy.calls.reset();
  });

  describe('when calling getThings', function() {
    it('should call get on the underlying resource instance', function() {
      myDataService.getThings(1, 15);
      expect(resourceSpy).toHaveBeenCalled();
    });
  });

我得到了Unknown provider: $resourceProvider <- $resource,我确保将角度资源作为我的Karma配置的一部分。

我也正在使用Karma的角度模拟,我确实想知道这是错误,因为$ resource不是模拟库的一部分?我没有声明任何角度模块作为测试的一部分加载,因为我只想隔离测试类,而不是必须加载整个模块。

由于

1 个答案:

答案 0 :(得分:0)

@PetrAveryanov有正确的答案。我要指出的是-除非在OP的Jasmine中进行了一些精美的骆驼案检查,但没有我的Jest副本,否则自该帖子起,该模块的名称已更改为ngResourcebeforeEach(angular.mock.module('ngResource'));