我整天试图用茉莉花做一个简单的测试,但是我认为我做错了。我有一段代码要测试,但是我不能进去。我试图遵循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
})
如果您能帮助我,谢谢,因为我已经浪费了很多时间。
答案 0 :(得分:0)
在ngrx版本中。 > 8.0.0,如果您在各个覆盖的选择器上使用store.refreshState
,则有一种方法store.setState
会刷新状态。不幸的是,refreshState
方法在ngrx 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)
});
答案 1 :(得分:0)
我对测试工作进行了一些更改。 1-删除了“ const initialState”并从我的应用状态文件中导入。 2-MockStore的类型,我更改为我的应用状态类型 3-在测试中,我将新值设置为'cepState.endereco'并使用initialState调用setState 4-我将'store'更改为'mockStore',但没有区别 5-最后,我带来了正确的导入
看下面的代码:
describe('FormComponent', () => {
let component: FormComponent;
let fixture: ComponentFixture<FormComponent>;
let mockStore: MockStore<AppState>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [FormComponent],
imports: [
StoreModule.forRoot({ 'cepState': CepReducer })
],
providers: [provideMockStore({ initialState })]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
mockStore = TestBed.get(Store);
});
it('should test new endereco state', () => {
initialState.cepState.endereco = RES
mockStore.setState(initialState)
expect(component.endereco).toEqual(RES)
});
});