如何模拟 History.state 以在 Angular 中编写单元测试

问题描述 投票:0回答:3

我正在为我的组件编写单元测试,但在创建组件实例并显示以下错误时遇到问题,

TypeError: Cannot read property 'patientId' of null 

我尝试模拟所有提供商,包括路由器和活动路由器 我的 component.ts 是

export class PatientInsurancePlanSearchComponent implements OnInit {

  private patientId: number = -1;
  public selectedOrganizationInsurance: OrganizationInsurance;
  public organizationInsurancePlans$: Observable<OrganizationInsurancePlan[]>;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private biilingHttpService: BillingHttpService
  ) {
    this.selectedOrganizationInsurance = new OrganizationInsurance();
  }

  ngOnInit() {
    this.patientId = history.state.patientId as number;
    this.selectedOrganizationInsurance = history.state.selectedOrganizationInsurance as OrganizationInsurance;
    this.organizationInsurancePlans$ = this.biilingHttpService.getOrganizationInsurancePlans(this.selectedOrganizationInsurance.id);
  }

规格ts

class FakeInsurancePlanSearchComponent {
  @Input() public organizationInsurancePlans: OrganizationInsurancePlan[] = [];
  @Input() public selectedOrganizationInsurance: OrganizationInsurance;
  }
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ PatientInsurancePlanSearchComponent
      , FakeInsurancePlanSearchComponent ],
      imports: [
        StoreModule.forRoot({}),
        HttpClientModule,
        RouterTestingModule,
      ],
      providers: [
        Store,
        {
          provide: ActivatedRoute, useValue: {
            state: of({ selectedorganizationInsurancePlan: 'AETNA'})
        }
      },
      BillingHttpService
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PatientInsurancePlanSearchComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

请指导我我缺少什么..

angular unit-testing karma-jasmine
3个回答
17
投票

如果你想将病人ID添加到浏览器会话历史堆栈中,你可以简单地使用:

history.pushState(state, title, url);

在你的情况下应该是这样的:

describe(MyComponent.name, () => {
   ...

   beforeEach(() => {
       window.history.pushState({ patientId: 'somevalue'}, '', '');

       ...
   })


   it('...', () => {

   })
}

0
投票

简单回答:

您可以提供以下状态:

provideMockStore({ initialState: your_state })

mockStore.setState(your_state );

但是如果您有一家复杂的商店,我建议您执行以下操作:

  • 创建一个类,您将在其中拥有模拟商店状态:
    MockStoreState

type RecursivePartial<T> = {
  [P in keyof T]?:
  T[P] extends (infer U)[] ? RecursivePartial<U>[] :
    T[P] extends object ? RecursivePartial<T[P]> :
      T[P];
};

export class MockStoreState {
  private store_a: RecursivePartial<Store_A>;
  private store_b: RecursivePartial<Store_b>;

  build(): any {
    const defaultStore_a = {
      ...
    };
    const defaultStore_b = {
      ...
    };

    return {
      store_a: { ...defaultStore_a , ...this.store_a},
      store_b: { ...defaultStore_b , ...this.store_b },
    };
  }

  setStore_a(value: RecursivePartial<Store_A>): Store_A_State {
    this.store_a= value;
    return this;
  }

  setStore_b(value: RecursivePartial<DatasourceState>): Store_B_State {
    this.store_b= value;
    return this;
  }
}
  • 在测试中设置您商店中的状态:
describe(MyComponent.name, () => {
   ...
   let mockStore: MockStore<any>;

   beforeEach(() => {
       ...
       mockStore = TestBed.get(Store);
   })


   it('...', () => {
     const state = new MockStoreState().setStore_a({...})
    .build();

    mockStore.setState(state);

   // HERE you have set the data in your store.
   })
}

0
投票

如果您使用 Jasmine 测试框架,您可以使用以下代码简单地模拟历史记录

spyOnProperty(window.history, 'state').and.returnValue({ patientId: someValue });
© www.soinside.com 2019 - 2024. All rights reserved.