【问题标题】:NullInjectorError: No provider for StoreNullInjectorError:商店没有提供者
【发布时间】:2018-12-06 20:53:03
【问题描述】:

我在运行单元测试时收到以下错误:

Error: StaticInjectorError(DynamicTestModule)[BlogService -> Store]: 
  StaticInjectorError(Platform: core)[BlogService -> Store]: 
    NullInjectorError: No provider for Store!

这是我的测试文件中的代码:

import { TestBed, inject } from '@angular/core/testing';

import { BlogService } from './blog.service';

describe('BlogService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [BlogService]
    });
  });

  it('should be created', inject([BlogService], (service: BlogService) => {
    expect(service).toBeTruthy();
  }));
});

我不确定为什么会发生此错误。我认为“注入”调用会实例化服务。

【问题讨论】:

    标签: angular unit-testing karma-jasmine


    【解决方案1】:

    如果您的服务引用了一个ngrx 存储,那么您需要导入ngrx 模块。我现在假设您正在 AppModule 中执行此操作。您需要在您的 TestBed 模块中复制它。我通常会创建一个测试 ngrx 模块来完成所有这些,然后我可以将它导入到任何引用 Store 的规范文件中

    【讨论】:

      【解决方案2】:

      如上所述here

      Add following to the specs.ts file:
      // Add the import the module from the package 
      import { StoreModule } from '@ngrx/store';
      
         // Add the imported module to the imports array in beforeEach 
         beforeEach(async(() => {
          TestBed.configureTestingModule({
            imports: [
              StoreModule.provideStore({})
            ],
            declarations: [
              // The component that's being tested
            ]
          })
          .compileComponents();
        }));
      

      如果您收到错误 Property 'provideStore' does not exist on type 'typeof StoreModule,请使用 forRoot instead of provideStore。 也看看here,这里有类似的问题here

      干杯!

      【讨论】:

      • 感谢您的解释。
      【解决方案3】:

      您可以使用 ngrx 模拟商店:

      import { provideMockStore } from '@ngrx/store/testing';
      
      beforeEach(() => {
          TestBed.configureTestingModule({
            providers: [provideMockStore({})],
          });
        });
      

      您可以定义特定状态并将其作为方法参数传递。

      【讨论】:

        猜你喜欢
        • 2020-06-26
        • 2019-11-16
        • 2021-01-20
        • 2019-06-25
        • 2018-09-19
        • 2018-05-02
        • 2020-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多