Angular Jest测试报错:this.store.select is not a function
Angular单元测试解决
this.store.select is not a function错误 问题出在你没有把定义好的mockStore注入到测试模块的Store提供者中,组件拿到的是未正确Mock的Store实例,自然找不到select方法。按以下步骤修改即可解决:
关联Mock实例到Store令牌
在测试模块的providers里,把原本的{provide: Store}替换成{provide: Store, useValue: mockStore},让组件构造函数注入的是你定义的Mock实例。让Mock的select返回可观察对象
组件中调用select后会执行subscribe,所以Mock的select必须返回一个可订阅的Observable,否则会触发新的报错。可以用rxjs的of创建一个模拟的数据流。
修改后的完整spec.ts代码示例:
import { of } from 'rxjs'; import { Store } from '@ngrx/store'; // 导入你的组件及其他必要依赖 const mockStore = { select: jest.fn().mockReturnValue(of({ name: '测试用户' })) // 返回模拟的用户数据Observable }; describe('你的组件名', () => { let component: 你的组件类名; let fixture: ComponentFixture<你的组件类名>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [RouterTestingModule, ReactiveFormsModule], declarations: [你的组件类名], providers: [ {provide: Store, useValue: mockStore} // 关键:注入MockStore ] }) .compileComponents(); fixture = TestBed.createComponent(你的组件类名); component = fixture.componentInstance; fixture.detectChanges(); }); it('应调用getData并订阅userData', () => { component.getData(); expect(mockStore.select).toHaveBeenCalledWith('userData'); // 验证调用参数 expect(component.userInfo).toEqual({ name: '测试用户' }); // 验证订阅后的数据赋值 }); });
如果后续需要测试dispatch方法,只需在mockStore中添加dispatch: jest.fn(),测试时直接验证mockStore.dispatch是否被调用即可。
内容的提问来源于stack exchange,提问作者Jorge Luiz Rodrigues
相关产品推荐
相关产品推荐

