Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;   }); 
like image 320
lorless Avatar asked Jan 29 '19 10:01

lorless


People also ask

How do you overwrite a Jasmine spy?

if are already spying on a method and you want the original method to be called instead you should call andCallThrough() which will override the first spy behavior.

What is Spy object in Jasmine?

Jasmine spy is another functionality which does the exact same as its name specifies. It will allow you to spy on your application function calls. There are two types of spying technology available in Jasmine.


2 Answers

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.

like image 120
Jelle Avatar answered Sep 24 '22 07:09

Jelle


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

like image 31
Yuvraj Patil Avatar answered Sep 26 '22 07:09

Yuvraj Patil