gpt4 book ai didi

angular - NgRX provideMockStore createSelector 状态未定义

转载 作者:行者123 更新时间:2023-12-02 16:20:59 26 4
gpt4 key购买 nike

使用 provide mockStore 时,我的功能/选择器函数只会将状态视为未定义。

因此,我只能模拟选择器,因此无法执行更完整的集成测试。

选择器是否不应该看到由模拟商店提供的状态,或者这应该有效吗?

创建模拟商店

     TestBed.configureTestingModule({
providers: [
AuthGuardGuard,
provideMockStore({
initialState: { ...initialState },
}),
],
});

然后记录选择器应该看到的状态,这是未定义的。

export const currentUser = createSelector(
authRootFeature,
(state: fromAuthRoot.State) => {
console.log(state); // Undefined
return state.auth.currentUser;
}
);

最佳答案

MockStore 应该设置状态,我将与您分享两个有效的实现,您可以选择您喜欢的实现,您的问题中缺少信息,因此很难指出为什么这对您不起作用。

这是一个:

我的选择器:

export const selectFeature = createFeatureSelector<State, FeatureState>('feature');

export const getFeatureProperty = createSelector(
selectFeature,
(state) => state.featureProperty
);

我的测试文件:

describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let mockStore: MockStore<State>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LogsMenuViewComponent, LogsMenuViewDropdownComponent],
providers: [provideMockStore({ initialState: { feature: { featureProperty: 123 } } as State })],
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
mockStore = TestBed.inject(Store) as MockStore<State>;
component = fixture.componentInstance;
fixture.detectChanges();
});
});

之所以可行,是因为我的选择器使用了一个特性,选择器,所以它能够正确地获取状态。

另一种可能对您有用的实现是覆盖选择器,如下所示:

  describe('selectors', () => {
let mockShowsSelector;
beforeEach(() => {
mockShowsSelector = store.overrideSelector(selectFavoriteShows, [{
id: 3,
name: 'C',
description: 'Show C',
imgUrl: '',
isFavorite: true
}]);
fixture.detectChanges();
});

it('should render all favorite shows', () => {
expect(fixture.debugElement.queryAll(By.css('.mat-card')).length).toBe(1);
});

it('should update the UI when the selector changes', () => {
mockShowsSelector.setResult([ // overide selector
{
id: 1,
name: 'A',
description: 'Show A',
imgUrl: '',
isFavorite: true
},
{
id: 2,
name: 'B',
description: 'Show B',
imgUrl: '',
isFavorite: true
}
]);
store.refreshState();
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('.mat-card')).length).toBe(2);
});
})

关于angular - NgRX provideMockStore createSelector 状态未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65527740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com