網站搜尋

typescript - Angular 6 ngrx store 測試:無法讀取未定義的 ids


我正在嘗試測試一個已注入 Store 的元件。測試未通過,並給我以下錯誤:"Cannot read property 'ids' of undefined"

測試:

 const initialState = {
    quoteInfo: {
        quoteLoaded: true,
        ids: [0],
        entities: {
            '0': {
                id: 0,
                quoteId: 'string',
                quoteStatus: 0,
                reference: 'ref01',
            }
        }
    },
    quoteSettings: {
        quoteSettingsReceived: true,
        ids: [1],
        entities: {
          '1': {
            id: 1,
            status: 0,
            customer: 'string',
            customerId: 'cus01',
            carrier: 'car01',
            contact: 'contact01',
            contactId: 'c01',
            priceCategory: 'vip',
            priceCategoryId: 'pr1',
            creationDate: null,
            expirationDate: null,
            deliveryDate: null,
            currency: null,
            currencyId: null,
            paymentDescription: 'pay desc',
            tax: 0,
            comments: 'comments',
            shippingAddress: null,
            billingAddress: null
          }
        }
    }
  };

在每次測試之前:

  beforeEach( async(() => {
    TestBed.configureTestingModule({
      declarations: [GeneralComponent],
      imports: [
        BrowserAnimationsModule,
        HttpClientModule,
        StoreModule.forRoot({ feature: combineReducers({quoteSettings: settingsReducer, quoteInfo: infoReducer }, initialState)}),
      ],
      providers: [
      ]
    }).compileComponents();
  }));

錯誤出現在元件初始化,其程式碼如下:

 ngOnInit() {
    this.randomObservable$ = this._store.pipe(select(randomSelector));
  }

隨機選擇器

export const randomFeatureSelector= createFeatureSelector<RandomState>('random');
export const randomSelector = createSelector(
  randomFeatureSelector, // this is null
  fromRandomReducer.selectAll
);

答案#1

問題出在 HTML 文件中,我直接使用了 selector 的 observable,如果 store 還沒有初始化,就會出現那個錯誤

答案#2

對於模擬 Store,我通常使用 rx.js 的 BehaviorSubject:

let mockStore;
beforeEach( async(() => {
 mockStore = new BehaviorSubject(initialState);
 TestBed.configureTestingModule({
  declarations: [GeneralComponent],
  imports: [
    BrowserAnimationsModule,
    HttpClientModule
  ],
  providers: [
  {provide: Store, useValue: mockStore}
  ]
}).compileComponents();

}));

...