我正在尝试测试可编辑购物清单项目的组件。首次加载时,它通过订阅store.select
收到的相关状态值是:
editedIngredient: null,
editedIngredientIndex: -1
使用这些值,将确保将类别的editMode
属性设置为false
。在测试期间,一旦组件加载,我将尝试更新状态。我正在尝试实现的是将editedIngredient
和editedIngredientIndex
属性更新为组件中的真实值,从而允许将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();
});
})
);
done()
回调,则不会进行更改检测。但是,如果包含done()
回调,则会出现错误,指出done() is not a function
供参考:我从the NgRx docs找到了模拟商店的示例(我在Angular 8上,所以这个示例与我最相关)
我正在使用Karma / Jasmine进行测试。
任何指导都会非常有帮助。
我正在尝试测试可编辑购物清单项目的组件。首次加载时,通过订阅store.select收到的相关状态值是:editedIngredient:null,...
经过一些研究,我认为我已经找到了问题。
由于Andrei的投入,我设法使ngrx/store
订户得到更新。以下是我需要做的: