San Jay Falcon
San Jay Falcon

Reputation: 1013

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

Trying to test dynamically caled functions, figurig out how to do this with a Spy. Suggestions are welcome.

I really want to emphasize that i am not looking for a Mock approach of the Object under test.

Currently implemented expectation doesnt work:

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

jumpTable

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

test

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

Upvotes: 0

Views: 523

Answers (1)

AliF50
AliF50

Reputation: 18889

You need to spy on store.dispatch before calling the function that calls it.

Try this:

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

Upvotes: 1

Related Questions