Cheatsheet - Jasmine

We reuse many things during any application development. While working with Jasmine, generally we use two sources, Jasmine Docs and Google. Even though we refer these resources, it consumes lot of time to get what we want i.e. right syntax with example.
To avoid doing this every time I have enlisted few of them as cheatsheet which can be used whenever required.
- Create spy object with spy methods
mySpy = jasmine.createSpyObj('Contact', ['get','set']);
2. Call fake method instead of real one.
mySpy.pickContact.and.callFake(function () {
return {
id: 10
};
});
3. Call a spy method and return a value
var contact = {
id: 10
};
mySpy.pickContact.and.returnValue(contact);
4. Call a spy method and return a async value
var contact = {
id: 10
};
mySpy.pickContact.and.returnValue(asyncData(contact));
5. Install a spy on existing object
spyOn(Contact, 'get'); // Spy on 'get' method of Contact
6. Install a spy on a property
spyOnProperty(Contact, 'name'); // Spy on 'name' property of Contact
7. Check spy method called or not
expect(Contact.get).toHaveBeenCalled(); // Check if called
expect(Contact.set).not.toHaveBeenCalled(); // Check if not called
8. Check spy method is called with particular parameters
expect(Contact.get).toHaveBeenCalledWith('Ganesh', 'Gaitonde');
9. Check call counts
expect(mySpy.get.calls.count()).toBe(1, ‘one call’);
10. Check most recent call
expect(mySpy.get.calls.mostRecent().args[1]).toEqual('getErr');
11. Reset Spy calls
var myService = jasmine.createSpyObj('MyService', ['getId']);myService.getId.calls.reset();
12. Override global spy in local file and reset it after all tests are executed.
...
const areArraysEqual = UvUtilService.areArraysEqual();
...it('applyFilters should apply Filters', () => {
...
expect(HomeService.filterCards).not.toHaveBeenCalled(); UvUtilService.areArraysEqual.and.callFake(() => {
return false;
});
expect(HomeService.filterCards).toHaveBeenCalled();
...
});afterAll(() => {
UvUtilService.areArraysEqual.and.callFake(() => {
return areArraysEqual;
});
});
13. fakeAsync()
with tick()
→ No actual call from spec file
14. async()
with fixture.whenStable()
→ Actual call from spec file