Search code examples
angularjasmine

How to reset withargs spystrategy?


How to clear a withArgs SpyStrategy? I couldn't find anything in the docs.

I will typically create a spy object like the following:

  let inventoryServiceSpy = jasmine.createSpyObj('InventoryService', [
    'getInventories'
  ]);

In my tests I'll provide arguments for generic calls like this: inventoryServiceSpy.getInventories.and.returnValue([someInventoryObject]);

To make sure this return value isn't shared among tests in my beforeEach I'll include the following: inventoryServiceSpy.getInventories.and.returnValue([]);

This works fine. However, in one test I am returning different values based on the parameters:

    inventoryServiceSpy.getInventories
      .withArgs('org1')
      .and.returnValue([org1Inv]);
    inventoryServiceSpy.getInventories
      .withArgs('org2')
      .and.returnValue([org2Inv]);

However, if this test runs before another that also happens to use 'org1' as an input, it will return the stored org1Inv rather than someInventoryObject. I assume it is doing this because withArgs isn't cleared in the beforeEach and the withArgs is taking precedence over the generic returnValue.

Is there a way to clear all withArgs values in beforeEach? Or clear it at the end of any test that uses it?


Solution

  • you can reinitialize the spy using beforeEach at the root level, this will ensure your code always runs with the initial state of the spy, this will ensure minimal side effects.

    beforeEach(() => {
        let inventoryServiceSpy = jasmine.createSpyObj('InventoryService', [
            'getInventories'
        ]);
    });
    

    Another solution will be

    reinitialize the angular component after each test case using beforeEach at the root level so that it will run after each test. This will clear all the spies and listeners and give you a clean state for testing.

    Please provide more code/stackblitz for detailed solution!