如何模拟History.state以角度编写单元测试

时间:2019-11-05 13:10:27

标签: angular unit-testing karma-jasmine

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

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);
  }

spec.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();
  });

请指导我我所缺少的。.

2 个答案:

答案 0 :(得分:3)

如果您想将PatientId添加到浏览器的会话历史记录堆栈中,只需使用:

history.pushState(state, title, url);

您的情况应该是这样的:

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

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

       ...
   })


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

   })
}

答案 1 :(得分: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.
   })
}