使用 Karma (Jasmine) 进行单元测试:动态调用对象中定义的函数

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

尝试测试动态缩放函数,弄清楚如何使用 Spy 执行此操作。欢迎提出建议。

我真的想强调我不是在寻找被测对象的模拟方法。

当前实现的期望不起作用:

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

试试这个:

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