首页 > 解决方案 > 如何设置新状态来测试可观察对象?

问题描述

我整天都在尝试用茉莉花做一个简单的测试,但我认为我做错了什么。我有一段代码要测试,但我不能进去。我试图遵循 nrgx 7 文档,但我失败了。

下面的单元测试应该测试我的 enderecoFeatureSubscription。store.setState({ cep: null, endereco: RES }) 对商店没有做任何事情,所以我的订阅没有做任何事情

  let component: FormComponent;
  let fixture: ComponentFixture<FormComponent>;
  let store: MockStore<ICepState>
  const initialState = {
    cep: null, endereco: null
  };
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [FormComponent],
      imports: [StoreModule.forRoot({}),],
      providers: [
        provideMockStore({ initialState: CEPSTATE })
      ]
    }).compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(FormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    store = TestBed.get(Store);
  });
  it('should test enderecoFeatureSubscription ', () => {
    store.setState({ cep: null, endereco: RES })
    expect(component.endereco).toEqual(RES)
  });

零件

private enderecoFeatureSubscription = this.store.pipe(select(enderecoFeatureSelector)).subscribe((endereco: IEndereco | any) => {
    if (!endereco) {
      return;
    }
    this.endereco = endereco
  })

如果你能帮助我谢谢你,因为我已经浪费了很多时间。

标签: jasminengrx

解决方案


在 ngrx 版本中。> 8.0.0,如果您在相应的覆盖选择器上使用,则有一种方法会store.refreshState刷新状态。store.setState不幸的是,refreshStatengrx 7 中不存在方法。还有一种替代方法 - 您应该使用store.overrideSelector这样的方法覆盖所需的选择器 -

it('should test enderecoFeatureSubscription ', () => {
    store.overrideSelector(enderecoFeatureSelector, <put you mocked value>
    fixture.detectChanges(); //MAKE sure to remove fixture.detectChanges() from beforeEach
    expect(component.endereco).toEqual(RES)
  });

推荐阅读