How to reset a spy in Jasmine?

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.


The mock service with the default return value can be set in the beforeEach() , but if you want to change the mocked service response later, do not call fixture.detectChanges() in beforEach, you can call it in each spec after applying required changes (if any), if you want to change the mock service response in an specific spec, then add it to that spec before the fixture.detectChanges()

  beforeEach(() => {
    serviceSpy = jasmine.createSpyObj('RealService', ['methodName']);
    serviceSpy.methodName.and.returnValue(defaultResponse);

    TestBed.configureTestingModule({
      providers: [{provide: RealService, useValue: serviceSpy }],
    ...
    })
    ...

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    // do not call fixture.detectChanges() here
  });

  it('test something with default mocked service response', () => {
      fixture.detectChanges();
      ....
  });

  it('test something with a new mocked service response', () => {
      serviceSpy.methodName.and.returnValue(newResponse);
      fixture.detectChanges();
      ....
  });

Type 1:

var myService = jasmine.createSpyObj('MyService', ['updateSelections']);

myService.updateSelections.calls.reset();


Type 2:

var myService = spyOn(MyService, 'updateSelections');

myService.updateSelections.calls.reset();

Note: Code above is tested on Jasmine 3.5