首页 > 解决方案 > Angular .pipe and .subscribe undefined when selecting from ngrx store in unit tests

问题描述

I had some previously working unit tests and at some point they stopped working.

Whenever I select an observable from the ngrx store like so:

const observable = this.store.select(isAuthenticated);

and then attempt to call .pipe or .subscribe, these functions are undefined.

observable.subscribe(authenticated => {});

TypeError: observable.subscribe is not a function

or

TypeError: _this.store.select(...).pipe is not a function

I am importing the StoreModule and adding the appropriate model. These components work fine when not testing.

Edit: I use this MockStore function to add data to the store to select. I suspect the problem is in the map function as this changed with rxjs 6. the store selection is returning a map function instead of an observable.

import { TestBed } from '@angular/core/testing';
import { Store } from '@ngrx/store';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';


export function MockStore(mockStore: any) {

  const mockData: BehaviorSubject<Object> = new BehaviorSubject<Object>(mockStore);

  const store = TestBed.get(Store);
  const storeSpy = spyOn(store, 'select').and.callFake((fn) => {
    return map.call(mockData, fn);
  });

  return storeSpy;
}

export function MockDispatch() {
  const store = TestBed.get(Store);
  const dispatchSpy = spyOn(store, 'dispatch').and.callFake(() => { return; });
  return dispatchSpy;
}

标签: angularunit-testingrxjsngrx

解决方案


原来我是从错误的区域导入地图

改变:

import { map } from 'rxjs/operators';

至:

import { map } from 'rxjs/operator/map';

一切又开始工作了。


推荐阅读