在 afterAll 中抛出错误:TypeError: 无法读取未定义的 'ids' 属性。

3

我是新手,正在学习Angular,并尝试为我的组件编写简单的单元测试。我的测试有时会失败,并出现以下错误:An error was thrown in afterAll TypeError: Cannot read property 'ids' of undefined。我也附上了错误追踪enter image description here

这是我的组件实现:

    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();
      });

你的 TopPanelComponent 中有 ngOnDestroy 方法吗?能否请展示一下它的代码? - IAfanasov
@IAfanasov 这是:ngOnDestroy():void { this.destroy.next(); this.destroy.complete(); } - Amila Eranda
似乎并不是错误源。我只能猜测在其他地方使用了 this. destroy。整个组件的代码可能有所帮助。您还可以尝试探索错误堆栈跟踪中的文件,那里可能会有一些线索。 - IAfanasov
@AmilaEranda 你能展示一下 STORE_MODULE_TEST 吗? - Buczkowski
@Buczkowski 这是:export const STORE_MODULE_TEST = StoreModule.forRoot({ ...fromRoot.reducers, 'core': combineReducers(fromCore.coreReducers) }, { runtimeChecks: { strictStateImmutability: true, strictActionImmutability: true, strictStateSerializability: false, strictActionSerializability: false } }); - Amila Eranda
1个回答

4

这是一种可能的解决方法,因为你的错误提示表明 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进行监测,在beforeEach中首次调用fixture.detectChanges();,因此ngOnInit将在监测前被执行。

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