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; });
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With