单元测试 – 模拟ngrx / store
发布时间:2020-12-17 06:53:36 所属栏目:安全 来源:网络整理
导读:这与Angular 2官方发布有关.我知道单元测试在beta,RC和官方发布之间发生了巨大变化. 当它在构造函数中用作参数时,在单元测试中模拟@ ngrx / store的好方法是什么?它并不像模拟服务那么简单. 例如,如果我想模拟服务,那么我可以这样做: let serviceStub = {
这与Angular 2官方发布有关.我知道单元测试在beta,RC和官方发布之间发生了巨大变化.
当它在构造函数中用作参数时,在单元测试中模拟@ ngrx / store的好方法是什么?它并不像模拟服务那么简单. 例如,如果我想模拟服务,那么我可以这样做: let serviceStub = { }; // not a true mocked service,just a stub,right? let de: DebugElement; let el: HTMLElement; let nativeEl: Element; let comp: Typeahead; let fixture: ComponentFixture<Typeahead>; describe('Component:Typeahead',() => { beforeEach(() => { TestBed.configureTestingModule({ imports: [...],declarations: [Typeahead],providers: [ {provide: TypeaheadService,useValue: serviceStub} // provides the service that is being "mocked" ] }).compileComponents(); fixture = TestBed.createComponent(Typeahead); nativeEl = fixture.nativeElement; comp = fixture.componentInstance; de = fixture.debugElement; }); }); 这很有效. 但是,对于ngrx / store,它不会(如果您将Store替换为TypeaheadService).我想你必须编写一个扩展Store的模拟类,然后将其提供给正在测试的组件,但我不确定为什么会这样(如果是这种情况). 我只是在如何在我的单元测试中模拟ngrx / store并且在他们的站点或github上找不到任何文档时感到困惑.也许我忽略了它. 解决方法
感谢您发布问题并建议可能的解决方案!
我嘲笑它的方法是,在每次测试之前使用实际动作设置初始状态,即模拟状态.这是一个例子 beforeEach(inject([Store],(store: Store<ApplicationState>) => { const someFakeState = { counter: 9,counterFilter: 'A_FAKE_COUNTER_FILTER' }; store.dispatch(new myActionToSetSomeData(someFakeState)); })); 在你的it()块中,你现在应该能够检查组件是否显示计数为9并且通过’A_FAKE_COUNTER_FILTER’进行过滤. 您当然可以在it块中设置状态,而不是beforeEach,只要它在组件实例化之前. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |