将服务注入工厂

时间:2017-07-24 08:22:00

标签: javascript angularjs typescript dependency-injection factory

我正在尝试将服务注入工厂,但测试会抛出两种不同类型的错误,具体取决于我是将服务注入构造函数还是作为私有静态变量导入。

注入内部构造函数



  import {MyService} from "../path";
  
  export class MyFactory() {
    constructor(private mySrv: MyService) {
      // usage example: this.mySrv.mySrvMethods(..blabla..)
    }
}




我的index.ts文件没有真正注入,当我运行应用程序时服务不存在。

注入工厂类的实例属性



import {MyService} from "../path";

class MyFactory() {

  private mySrv: MyService;
  constructor() {}
  // Usage: MyFactory.mySrv.mySrvMethods()
}




这也会引发TypeError: undefined is not an object (evaluating MyFactory.mySrv.mySrvMethod) ....

我在测试中注入这些的方式是:



describe('MyFactory', function() {
  var myService, myFactory, others;
  beforeEach(inject(function(myFactory, myService, others) {
    myFactory = myFactory;
    myService = myService;
  })
);
describe('my factory method 1', function() {
 spyOn(myService, 'mySrvMethod1').and.returnValue('random test');
 // myService is not injected as it says undefined
});




0 个答案:

没有答案