0 day streak
javascript / intermediate
Snippet

Mocking Dependencies with Jasmine Spies

When testing Angular components, you should isolate them by mocking their dependencies. Jasmine 'spies' allow you to track calls to a function and define what it should return, preventing actual HTTP calls or side effects during tests.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
it('should fetch data on init', () => {
const service = TestBed.inject(DataService);
const spy = spyOn(service, 'getData').and.returnValue(of(['Item 1']));
component.ngOnInit();
expect(spy).toHaveBeenCalled();
expect(component.items).toEqual(['Item 1']);
});
angular
Breakdown
1
spyOn(service, 'getData')
Creates a wrapper around the service method to intercept its execution.
2
and.returnValue(of(['Item 1']))
Forces the spy to return a mock Observable instead of executing the original logic.