NgRx测试-测试期间订阅回调未更新

问题描述 投票:1回答:2

我正在尝试测试可编辑购物清单项目的组件。首次加载时,它通过订阅store.select收到的相关状态值是:

editedIngredient: null,
editedIngredientIndex: -1

使用这些值,将确保将类别的editMode属性设置为false。在测试期间,一旦组件加载,我将尝试更新状态。我正在尝试实现的是将editedIngredienteditedIngredientIndex属性更新为组件中的真实值,从而允许将editMode属性设置为true

[尝试下面的代码时,我能够渲染该组件,并且editMode最初设置为false。但是,一旦状态在我的测试中更新,store.select订阅者就不会更新,这意味着测试会在editMode从未设置为true的情况下完成。

组件代码(ShoppingEditComponent)

ngOnInit() {
  this._subscription = this.store.select('shoppingList').subscribe(stateData => {
    if (stateData.editedIngredientIndex > -1) {
      this.editMode = true; // I want to update my state later so that I set this value
      return;
    }
    this.editMode = false; // I start with this value
  });
}

测试代码

let store: MockStore<State>;
const initialState: State = {
  editedIngredient: null,
  editedIngredientIndex: -1
};
const updatedShoppingListState: State = {
  editedIngredient: seedData[0],
  editedIngredientIndex: 0
};

let storeMock;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [
        ShoppingEditComponent
      ],
      providers: [
        provideMockStore({ initialState }),
      ]
    });
});

测试尝试1

it('should have \'editMode = true\' when it receives a selected ingredient in updated state',
  fakeAsync(() => {
    const fixture = TestBed.createComponent(ShoppingEditComponent);
    const componentInstance = fixture.componentInstance;

    // no change detection occurs, hence the subscribe callback does not get called with state update
    store.setState(updatedShoppingListState); 
    expect(componentInstance['editMode']).toEqual(true);
  })
);

测试尝试2

it('should have \'editMode = true\' when it receives a selected ingredient in updated state',
  fakeAsync((done) => {
    const fixture = TestBed.createComponent(ShoppingEditComponent);
    const componentInstance = fixture.componentInstance;
    fixture.whenStable().then(() => {
      store.setState(updatedShoppingListState);
      expect(componentInstance['editMode']).toEqual(true);
      done();
    });
  })
);
  • 我在尝试1时遇到的问题是未发生更改检测。
  • 我在尝试2时遇到的问题是,如果省略done()回调,则不会进行更改检测。但是,如果包含done()回调,则会出现错误,指出done() is not a function
  • 供参考:我从the NgRx docs找到了模拟商店的示例(我在Angular 8上,所以这个示例与我最相关)

我正在使用Karma / Jasmine进行测试。

任何指导都会非常有帮助。

我正在尝试测试可编辑购物清单项目的组件。首次加载时,通过订阅store.select收到的相关状态值是:editedIngredient:null,...

angular unit-testing rxjs karma-jasmine ngrx
2个回答
1
投票

经过一些研究,我认为我已经找到了问题。


0
投票

由于Andrei的投入,我设法使ngrx/store订户得到更新。以下是我需要做的:

© www.soinside.com 2019 - 2024. All rights reserved.