编辑:我想通了,问题是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
我的单元测试,但没有运气。现在已经搜索了几个小时:(。