【问题标题】:Testing @select decorators with @angular-redux/store使用 @angular-redux/store 测试 @select 装饰器
【发布时间】:2017-11-08 17:59:46
【问题描述】:

在 Angular 中测试依赖于 @select() 装饰器的组件时,我使用 MockNgRedux.getSelectorStub('myStoreProperty').next(testState) 向订阅者发送新值,但是当我调用下一个函数时,它不会触发具有新值的订阅。

查看示例代码:

export class BasicInfoComponent {
    @select() application$: Observable<Application>;
    this.application$.subscribe((app: Application) => { 
        //... this code is never triggered.
    }

}

这是测试设置

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [BasicInfoComponent],
      imports: [
        NgReduxTestingModule,
        ReactiveFormsModule
      ],
      providers: [
       //... providers
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicInfoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    MockNgRedux.reset();
  });

  afterEach(() => {
    fixture.destroy();
  });

【问题讨论】:

    标签: angular unit-testing testing redux


    【解决方案1】:

    您必须在创建组件之前调用MockNgRedux.reset()。 MockNgRedux 连接到在测试期间创建的所有 @select 装饰器,在组件创建 @select 装饰器后调用 reset 将断开 MockNgRedux 与其当前连接的所有装饰器的连接。

    beforeEach 函数修改为如下所示:

    beforeEach(() => {
        // NOTE: MockNgRedux Reset must happen before the creation of the component
        // otherwise it will reset the connections to the select decorators.
        MockNgRedux.reset();
        fixture = TestBed.createComponent(BasicInfoComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,但这是因为我在 @select(...) 中使用了 lambda 选择。似乎MockNgRedux 需要您使用与@select(...) 使用的完全相同的选择器来调用getSelectorStub

      所以,如果你有

      const selectorStub = MockNgRedux.getSelectorStub(['status', 'text']);
      

      那么你还需要在组件中同样的方式选择它:

      @select(['status', 'text'])
      readonly statusText: Observable<string>;
      

      【讨论】:

        猜你喜欢
        • 2019-04-21
        • 2019-06-16
        • 1970-01-01
        • 2011-02-13
        • 1970-01-01
        • 2017-08-20
        • 2012-02-14
        • 2019-02-21
        • 2016-02-29
        相关资源
        最近更新 更多