typescript - Angular 6 testování ngrx store: nelze číst ids z undefined
Snažím se otestovat komponentu, která má injektovaný Store. Test neprojde a zobrazí mi následující chybu: „Nelze číst vlastnost 'ids' z undefined“
Test :
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
}
}
}
};
Test beforeEach:
beforeEach( async(() => {
TestBed.configureTestingModule({
declarations: [GeneralComponent],
imports: [
BrowserAnimationsModule,
HttpClientModule,
StoreModule.forRoot({ feature: combineReducers({quoteSettings: settingsReducer, quoteInfo: infoReducer }, initialState)}),
],
providers: [
]
}).compileComponents();
}));
Chyba se objevuje při inicializaci komponenty, jejíž kód je následující:
ngOnInit() {
this.randomObservable$ = this._store.pipe(select(randomSelector));
}
Náhodný výběr
export const randomFeatureSelector= createFeatureSelector<RandomState>('random');
export const randomSelector = createSelector(
randomFeatureSelector, // this is null
fromRandomReducer.selectAll
);
Odpověď č. 1
Problém byl v HTML souboru, kde jsem přímo používal observable ze selectoru, a pokud obchod ještě nebyl inicializován, vyvolá to tuto chybu.
Odpověď č. 2
Pro mockování Store obvykle používám BehaviorSubject z rx.js:
let mockStore;
beforeEach( async(() => {
mockStore = new BehaviorSubject(initialState);
TestBed.configureTestingModule({
declarations: [GeneralComponent],
imports: [
BrowserAnimationsModule,
HttpClientModule
],
providers: [
{provide: Store, useValue: mockStore}
]
}).compileComponents();
}));
...
