Sometimes, we want to mock one specific method of a class with Jest and JavaScript.
In this article, we’ll look at how to mock one specific method of a class with Jest and JavaScript.
How to mock one specific method of a class with Jest and JavaScript?
To mock one specific method of a class with Jest and JavaScript, we can use the jest.spyOn
method.
For instance, we write
import Person from "./Person";
test("Modify only instance", () => {
let person = new Person("foo", "bar");
let spy = jest.spyOn(person, "sayMyName").mockImplementation(() => "Hello");
expect(person.sayMyName()).toBe("Hello");
expect(person.bla()).toBe("bla");
spy.mockRestore();
});
to mock the person.sayMyName
method by calling spyOn
and mockImplementation
in the test.
The mockImplementation
callback has the faked implementation of person.sayMyName
.
Likewise, we can mock the same method for all tests by writing
import Person from "./Person";
beforeAll(() => {
jest.spyOn(Person.prototype, "sayMyName").mockImplementation(() => "Hello");
});
afterAll(() => {
jest.restoreAllMocks();
});
test("Modify class", () => {
let person = new Person("foo", "bar");
expect(person.sayMyName()).toBe("Hello");
});
We call jest.spyOn
with Person.prototype
and 'sayMyName
and mockImplementation
to do the mocking in the beforeAll
callback.
The beforeAll
callback runs before any tests are run.
Then we call restoreAllMocks
to restore all mocks after all tests are run.
Conclusion
To mock one specific method of a class with Jest and JavaScript, we can use the jest.spyOn
method.