Search code examples
javascriptangularjasmine

How to reset a spy in Jasmine?


I have an issue where I've set up a mock service as a spy.

 mockSelectionsService = jasmine.createSpyObj(['updateSelections']);

I then call that stub method twice, each time in a different test. The problem is that when i expect() the spy with .toHaveBeenCalledWith() the toHaveBeenCalledWith method also contains the arguments it was passed from the first test which produces a false positive on my second test.

How do I wipe/clear/reset the spyObject for my next test so that it no longer believes it as been called at all?

Initialisation of services/components

  beforeEach(() => {
    mockSelectionsService = jasmine.createSpyObj(['updateSelections']);

    TestBed.configureTestingModule({
      declarations: [QuickSearchComponent, LoaderComponent, SearchComponent, SearchPipe, OrderByPipe],
      providers: [OrderByPipe, SearchPipe, SlicePipe, {provide: SelectionsService, useValue: mockSelectionsService}],
      imports: [FormsModule, HttpClientModule]
    });


    fixture = TestBed.createComponent(QuickSearchComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    fixture.componentInstance.templates = mockTemplates;
    fixture.componentInstance.manufacturers = mockManufacturers;
  });

Solution

  • const spy = spyOn(somethingService, "doSomething");

    spy.calls.reset();

    This resets the already made calls to the spy. This way you can reuse the spy between tests. The other way would be to nest the tests in another describe() and put a beforeEach() in it too.