簡體   English   中英

如何模擬 History.state 用於在 angular 中編寫單元測試

[英]How to Mock History.state for writing unit tests in angular

我正在為我的組件編寫單元測試,但在創建組件實例時遇到問題並顯示以下錯誤,

TypeError: Cannot read property 'patientId' of null 

我已經嘗試過 mocking 所有提供商,包括路由器和活動路由器 我的 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);
  }

規格

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

請指導我我缺少什么..

如果您想將 patientId 添加到瀏覽器 session 歷史堆棧中,您可以簡單地使用:

history.pushState(state, title, url);

在您的情況下,它應該是這樣的:

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

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

       ...
   })


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

   })
}

簡單的回答:

您可以在以下位置提供 state:

provideMockStore({ initialState: your_state })

或者

mockStore.setState(your_state );

如果您有一家復雜的商店,我建議您執行以下操作:

  • 創建一個 class ,您將在其中擁有模擬商店 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;
  }
}
  • 在您的商店中設置 state 在測試中:
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.
   })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM