簡體   English   中英

使用 Karma (Jasmine) 進行單元測試:在 Object 中定義的動態調用函數

[英]Unit Testing with Karma (Jasmine): dynamically called functions defined in Object

嘗試測試動態調用的函數,弄清楚如何使用 Spy 執行此操作。 歡迎提出建議。

我真的想強調,我不是在尋找正在測試的 Object 的 Mock 方法。

當前實現的期望不起作用:

Expected spy dispatch to have been called with: [ <jasmine.objectContaining(Object({ type: 'userEdit' }))> ] but it was never called.

跳轉表

public jumpTable: {} = {
  [ComponentState.USER_EDIT]: (componentState: ComponentState, userModel: IUserModel) => {
    this.store.dispatch({ type: USER_EDIT, payload: { userModel } });
  }
}

測試

  it(`should have jumpTable object with accoring keys`, () => {
    component.userModel = userIndy;
    fixture.detectChanges();

    // evaluates to true
    expect(component.jumpTable[ComponentState.USER_EDIT]).toBeDefined();

    // error > USER_EDIT does not resolve
    // const jumpDispatchStoreSpy = spyOn(component.jumpTable, USER_EDIT).and.callThrough();

    component.jumpTable[ComponentState.USER_EDIT](ComponentState.USER_EDIT, component.userModel);

    const storeSpy = spyOn(component.store, 'dispatch').and.callThrough();
    const dispatchObject = { type: USER_EDIT };
    expect(storeSpy).toHaveBeenCalledWith(jasmine.objectContaining(dispatchObject));
  });

在調用調用它的store.dispatch之前,您需要監視 store.dispatch。

嘗試這個:

it(`should have jumpTable object with accoring keys`, () => {
    component.userModel = userIndy;
    fixture.detectChanges();

    // evaluates to true
    expect(component.jumpTable[ComponentState.USER_EDIT]).toBeDefined();

    // error > USER_EDIT does not resolve
    // const jumpDispatchStoreSpy = spyOn(component.jumpTable, USER_EDIT).and.callThrough();
    // spy first on the dispatch
    const storeSpy = spyOn(component.store, 'dispatch').and.callThrough();
    // call method that calls dispatch
    component.jumpTable[ComponentState.USER_EDIT](ComponentState.USER_EDIT, component.userModel);

    const dispatchObject = { type: USER_EDIT };
    expect(storeSpy).toHaveBeenCalled();
    expect(storeSpy).toHaveBeenCalledWith(jasmine.objectContaining(dispatchObject));
  });

暫無
暫無

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

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