【问题标题】:Angular tests fail with takeWhile()角度测试因 takeWhile() 而失败
【发布时间】:2019-09-06 12:34:06
【问题描述】:

我有一个组件在使用 select 订阅 NgRx 减速器时使用 takeWhile()。因此:

    this.store.pipe(select(reducer.getProviders))
            .takeWhile( ... )
            .subscribe(providers => {
                ...
            });

现在我想为它编写测试。目前它非常基本:

    import { StoreModule, Store, Action, select, combineReducers } from '@ngrx/store';
    import { Subject } from 'rxjs/Subject';

    import * as reducer from './../../reducers';

    describe('ProviderComponent', () => {
        let component: ProviderComponent;
        let fixture: ComponentFixture<ProviderComponent>;
        let store: Store<reducer.State>;

        beforeEach(async(() => {
            const actions = new Subject<Action>();
            const states = new Subject<reducer.State>();
            store = mockStore<reducer.State>({ actions, states });

            TestBed.configureTestingModule({
                imports: [
                    StoreModule.forRoot({
                        provider: combineReducers(reducer.reducers)
                    }),
                    ...
                ],
                declarations: [
                    ProviderComponent
                ],
                providers: [
                    { provide: Store, useValue: store },
                    { provide: HAMMER_LOADER, useValue: () => new Promise(() => { return; }) }
                ]
            })
            fixture = TestBed.createComponent(ProviderComponent);
            component = fixture.componentInstance;
            component.providerCtrl = new FormControl();
            spyOn(store, 'dispatch').and.callThrough();
        }));

        describe('When provider is rendered', () => {
            beforeEach(() => {
                fixture.detectChanges();
            });

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

            it('store to be defined', async(() => {
                expect(store).toBeDefined();
            }));
        });
    });

但是当我运行它时,我得到了这个错误:

TypeError: this.store.pipe(...).takeWhile is not a function

不知道怎么导入! 谁能帮我解决这个问题?

【问题讨论】:

  • takeWhile 是一个运算符,就像 select。它进入管道方法,作为参数=.pipe(select(...), takeWhile(...))。并且 Subject 必须从 rxjs 导入,而不是 rxjs/Subject

标签: angular rxjs ngrx ngrx-store


【解决方案1】:

takeWhile 是一个支持管道的操作符,应该包含在管道中:

this.store.pipe(
   select(reducer.getProviders),
   takeWhile( ... ) 
).subscribe(providers => {
    ...
});

【讨论】:

    【解决方案2】:

    需要在组件中导入takewhile操作符

    import 'rxjs/add/operator/takeWhile';
    

    对于 rxjs 5.5 以上使用下面的语句

    import { takeWhile } from 'rxjs/operators';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 2012-05-27
      • 2019-05-01
      相关资源
      最近更新 更多