NullInjectorError: Store 没有提供者

Kod*_*_12 12 unit-testing karma-jasmine angular

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

Error: StaticInjectorError(DynamicTestModule)[BlogService -> Store]: 
  StaticInjectorError(Platform: core)[BlogService -> Store]: 
    NullInjectorError: No provider for Store!
Run Code Online (Sandbox Code Playgroud)

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

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();
  }));
});
Run Code Online (Sandbox Code Playgroud)

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

Jul*_*ida 23

您可以使用 ngrx 模拟商店:

import { provideMockStore } from '@ngrx/store/testing';

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideMockStore({})],
    });
  });
Run Code Online (Sandbox Code Playgroud)

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


Jas*_*son 10

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


小智 6

如前所述这里

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();
  }));
Run Code Online (Sandbox Code Playgroud)

如果您遇到错误,请Property 'provideStore' does not exist on type 'typeof StoreModule使用 forRoot insteadof provideStore. 另外,也要看看这里,这里是类似的问题在这里

干杯!