how to create mock object in jasmine

Rupesh Kumar Tiwari
1 min readMar 12, 2020

--

While writing test in jasmine you will encounter a situation where you want to create a mock object & also you want to spy it’s property.

Jasmine createSpyObj allows you to create an object only with methods. However suppose you object has some properties as well. Then how will you create a complete mocked object in jasmine such that both of it’s properties and methods are spied ?

Lets see below example You want to create a complete mock object of Person.

function Person(name) {
this.name = name;
greet() {
return `Hello ${this.name}`;
}
}

In Jasmine there is nothing readymade for this. However here is the trick. First create an person object and copy all of its methods by using jasmin.createSpyObj next one by one you can create spy on it’s property using createSpy method.

const person = {
…jasmine.createSpyObj(‘person’, ),
name :jasmine.createSpy();
}

--

--

Rupesh Kumar Tiwari
Rupesh Kumar Tiwari

Written by Rupesh Kumar Tiwari

Pluralsight Author, Developer and Trainer. I help students and professionals to become Full Stack Software Developer in less than a Year.

No responses yet