Skip to content

Instantly share code, notes, and snippets.

@AhsanAyaz
Last active June 26, 2023 01:58
Show Gist options
  • Save AhsanAyaz/8fc8425009a420369bc3e6c300bb6071 to your computer and use it in GitHub Desktop.
Save AhsanAyaz/8fc8425009a420369bc3e6c300bb6071 to your computer and use it in GitHub Desktop.
Angular Cookbook ng-jest-services-stubs tests for CounterService
// replace the tests below
it('should call the CounterService.getFromStorage method on component init', () => {
jest.spyOn(CounterServiceMock, 'getFromStorage');
component.ngOnInit();
expect(component.counterService.getFromStorage).toHaveBeenCalled();
});
it('should retrieve the last saved value from CounterService on component init', () => {
jest.spyOn(CounterServiceMock, 'getFromStorage').mockReturnValue(12);
component.counterService.saveToStorage(12);
component.ngOnInit();
expect(component.counter).toBe(12);
});
it('should save the new counterValue to CounterService on increment, decrement and reset', () => {
jest.spyOn(localStorage, 'setItem');
component.counter = 0;
component.increment();
expect(CounterServiceMock.saveToStorage).toHaveBeenCalledWith(1);
component.counter = 20;
component.decrement();
expect(CounterServiceMock.saveToStorage).toHaveBeenCalledWith(19);
component.reset();
expect(CounterServiceMock.saveToStorage).toHaveBeenCalledWith(0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment