Angular - Karma - ngrx - 无提供商 Store

11
在我的一个单元测试中,我试图模拟 @ngrx/store。我已经在另一个 spec 文件中成功地使用了这种技术,但是当我尝试在这个文件中使用它时,我得到了一个注入错误,说“没有 Store 的提供者!”。下面是来自 spec 文件的相关代码:
beforeEach(async(() => {
  const emptyState = { opportunities: { list: { items: [], page: 1, total: 0 } } };
  const mockStore = new MockStore<MockAppState>(emptyState);

  TestBed.configureTestingModule({
    declarations: [
      OpportunityListComponent,
      FilledArrayPipe
    ],
    imports: [
      NgFilterListModule,
      FormsModule
    ],
    providers: [
      { provide: OpportunityApi, useValue: apiStub },
      { provide: Store, useValue: mockStore },
      { provide: Router, useValue: routerStub }
    ]
  }).compileComponents();
}));

beforeEach(() => {
  store = fixture.debugElement.injector.get('Store');
});

这个组件和成功使用MockStore类的那个组件唯一的区别在于,这个组件是在自己的模块中进行懒加载,而不是在AppModule中。然而,我尝试在该模块中导入StoreModule,并将StoreModule包含在TestBed导入中,但都没有成功。
3个回答

7
您应该添加 <\p>
 imports: [
  ...,
 StoreModule.forRoot(fromRoot.reducers),
],

那可能会对你有所帮助


5

在 NgRx 7 及以上版本中,可像这样使用 MockStore

const initialState = {};
  
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LogsNewComponent],
      providers: [
        provideMockStore({ initialState }),
      ],
    }).compileComponents();
  }));


这是NGRX 7+还是8+?据我所知,这在7+版本中无法正常工作。 - JKennedy
应该可以工作,文档中也有说明: https://ngrx.io/guide/store/testing - Yair Cohen
1
是的,你说得对...我弄错了我的导入。我还发现了V7文档,它很有用。谢谢。 - JKennedy

5
原来我的问题在于我在fixture.debugElement.injector.get('Store')中引用了Store。移除引号后问题得到解决。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接