单元测试中的mock Observable concatMap函数(Angular 5)

时间:2017-12-27 08:42:00

标签: unit-testing angular5 ngrx-store angular-unit-test concatmap

编辑:我发现问题,问题是spyOn会使其侦测的函数返回undefined,需要明确调用and.callThough

我正在尝试测试使用ngrx存储的组件。我在这个单元测试中存储了我的商店:

meetup-view.component.spec.ts

class ActivatedRouteStub {
  private subject = new Subject();

  push(value) {
    this.subject.next(value);
  }

  get params() {
    return this.subject.asObservable();
  }
}

class StoreStub {
  storeState = {
    auth: Observable.of({}),
    meetups: Observable.of([{key: '1'}])
  };

  select(value) {
    return this.storeState[value];
  }

  dispatch() {

  }
}

describe('MeetupCreateComponent', () => {
  let component: MeetupCreateComponent;
  let fixture: ComponentFixture<MeetupCreateComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [ MeetupCreateComponent ],
      providers: [
        { provide: ActivatedRoute, useClass: ActivatedRouteStub },
        { provide: Store, useClass: StoreStub }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MeetupCreateComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should init edit/view mode correctly', () => {
    const route: ActivatedRouteStub = TestBed.get(ActivatedRoute);
    const store: StoreStub = TestBed.get(Store);
    const spy = spyOn(store, 'select').and.callThrough();
    route.push({id: 1});
    expect(spy).toHaveBeenCalled();
    expect(component.editMode).toBe(true);
  });
});

问题是,在我的组件中,我使用concatMap(并使用import 'rxjs/add/operator/concatMap';导入它)

meetup-view.component.ts

this.meetup$ = this.store.select('meetups')
        .concatMap(meetups => {
          return meetups.filter(m => m.key === key);
        });

当我运行单元测试时,我总是收到此错误:Cannot read property 'concatMap' of undefined。 我已经尝试将concatMap导入我的单元测试但没有运气。现在正在寻找几个小时:(。

0 个答案:

没有答案