Error with SpyObj how to reassign the value of spy

145 Views Asked by At

I'm fairly new to Jasmine so excuse my silly question.

I'm trying to override the value of the spy only for one it block and I'm hitting issues.

I'm seeing ERROR: <spyOn> : ActionsEnabled has already been spied upon error. How do i fix this?

Here is my code:

describe('Side Pane', () => {
  const state = cleanState<{
    component: Component,
    store: Store<{}>,
  }>(() => {
    spyOn(Flags, 'ActionsEnabled').and.returnValue(true);

    setupHybridModule({
      imports:
          [ActionsModule],
      providers: []
    });

    const store = get(Store);

    return {component: bootstrap(Actions), store};
  }, beforeEach);


  it('expects component to be hidden by default', () => {
    // I want to disable the flag and test
    spyOn(Flags, 'ActionsEnabled').and.returnValue(false); // ERROR: <spyOn> : ActionsEnabled has already been spied upon
    expect(hasEl('.actions-header')).toBeFalse();
  });

I'd appreciate some insights on what I'm doing wrong.

1

There are 1 best solutions below

3
AliF50 On

It's one of the quirks of Jasmine where if something has been spied on, it cannot be spied upon again. To fix this issue, you can assign the spyOn to a "global" variable within the describe block and then use this "global" variable to change the value.

Follow comments with !!:

describe('Side Pane', () => {
  // !! Declare the actionsEnabledSpy that will be a spy later on.
  let actionsEnabledSpy: jasmine.Spy;
  const state = cleanState<{
    component: Component,
    store: Store<{}>,
  }>(() => {
    // !! Assign the spyOn to the actionsEnabledSpy
    actionsEnabledSpy = spyOn(Flags, 'ActionsEnabled').and.returnValue(true);

    setupHybridModule({
      imports:
          [ActionsModule],
      providers: []
    });

    const store = get(Store);

    return {component: bootstrap(Actions), store};
  }, beforeEach);


  it('expects component to be hidden by default', () => {
    // I want to disable the flag and test
    // !! Over here, use the actionsEnabledSpy to change the value
    actionsEnabledSpy.and.returnValue(false);
    // !! You can also get other methods on actionsEnabledSpy like reset() to reset the spy (clear out all the times it was called).
    expect(hasEl('.actions-header')).toBeFalse();
  });