我是angular的新手,我尝试为我的组件编写简单的单元测试。我的测试无法按时完成,但出现以下错误:afterAll TypeError中引发了错误:无法读取未定义的属性'ids',并且我还附加了错误跟踪
这是我的组件实现:
ngOnInit() {
this.groupValueForm.valueChanges.subscribe((group: BasicGroup) => {
this.store.dispatch(GroupActions.selectGroup({ group: group }));
});
this.store.dispatch(GroupActions.getAllGroups());
this.store.pipe(select(selectAllGroups)).subscribe((basicGroups: BasicGroup[]) => {
this.groups = basicGroups;
});
}
这是我的测试类实现:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TopPanelModule,
STORE_MODULE_TEST
],
providers: [
{ provide: COUNTRY_ID, useValue: 'sv-SE' },
{ provide: TranslateService, useValue: mockTranslateService },
provideMockStore({ initialState })
]
});
store = TestBed.inject(MockStore);
fixture = TestBed.createComponent(TopPanelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should use the groupList from store', (done: DoneFn) => {
spyOn(store, 'pipe').and.returnValue(of(groups));
component.ngOnInit();
store.pipe().subscribe(resp=>{
expect(component.groups).toEqual(groups);
done();
})
});
it('should dispatch getAllGroups', () => {
spyOn(component['store'], 'dispatch');
component.ngOnInit();
expect(component['store'].dispatch).toHaveBeenCalledWith(GroupActions.getAllGroups());
});
afterEach(() => {
fixture.destroy();
});
答案 0 :(得分:0)
这是潜在的解决方法之一,因为您的错误提示yourEntityFeatureSliceName
(在以下情况下)为undefined
。另一方面,如果您不想覆盖初始状态,则可以始终覆盖选择器,正如我在评论中所写,它可以是selectAll
或selectEntities
-selectAllGroups
。
import {MockStore, provideMockStore} from '@ngrx/store/testing';
let store$: MockStore;
beforeEach(() => {
TestBed.configureTestingModule({
// Put other dependencies
providers: [
provideMockStore({
initialState: {
yourEntityFeatureSliceName: { // Update name
ids: [],
entities: {}
}
}
})
]
});
store$ = TestBed.inject(MockStore);
});
覆盖选择器:
store.overrideSelector(selectAllGroups, {}); // Provide data
除此之外,请注意,您在测试用例中监视store.pipe
,并且第一个fixture.detectChanges();
调用位于beforeEach
中,因此ngOnInit
将在监视之前执行。