【问题标题】:Angular Unit Test - How to inject dependencies to TestBed by using useValue in the TestBed providerAngular Unit Test - 如何在 TestBed 提供程序中使用 useValue 将依赖项注入到 TestBed
【发布时间】:2019-10-24 21:49:10
【问题描述】:

我要测试的服务有如下构造函数:

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

environment 由提供者下的 app.module 提供:

{ provide: 'environment', useValue: environment }

所以我将TestBed配置如下:

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

我不断得到:

错误:StaticInjectorError(DynamicTestModule)[环境]: StaticInjectorError(平台:核心)[环境]: NullInjectorError:没有环境提供者!

代码本身在服务/构建时运行良好,所以我认为错误在于我如何配置 TestBed?我也试过useFactory 无济于事。

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

【问题讨论】:

  • 我想帮助解决这个问题,因为我已经多次完成这种测试情况,但我需要查看更多代码。你能提供完整的规范文件和完整的组件文件吗?当然,如果完全不相关,您可以删除内容,但至少需要查看文件的结构。
  • nvm 我想我找到了你的问题
  • 非常感谢:D

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


【解决方案1】:

我认为这只是一个错字。

它缺少环境中的nnment

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 2014-11-07
    • 2018-11-21
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多