Angular Unit Test-如何通过使用TestBed提供程序中的useValue将依赖项注入TedBed

时间:2019-06-10 13:23:44

标签: angular typescript unit-testing angular-test testbed

我要测试的服务具有以下构造函数

constructor(@Inject('enviroment') environment) {
    this.initConfig(environment);
}

app.module中提供者提供的环境是

{ provide: 'environment', useValue: environment }

所以我按如下方式配置了TestBed

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [{ provide: 'environment', useValue: testEnv }, TestService]
    });
    service = TestBed.get(TestService);
});

我不断得到

 Error: StaticInjectorError(DynamicTestModule)[enviroment]: 
      StaticInjectorError(Platform: core)[enviroment]: 
        NullInjectorError: No provider for enviroment!

服务/构建时,代码本身可以正常工作,因此我认为错误是在配置TestBed的某个地方?我也尝试过useFactory无济于事。

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [{ provide: 'environment', useFactory: ()=>testEnv }, TestService]
    });
    service = TestBed.get(TestService);
});

1 个答案:

答案 0 :(得分:1)

我认为这只是一个错字

在环境中缺少n

constructor(@Inject('enviroment') environment) {