Using Jest's spyOn Function
Learn to use Jest’s spyOn function in this lesson.
Starter project
The project for this lesson is the completed project from the last lesson. In this lesson, we’ll refactor the test to use Jest’s spyOn
function.
A copy of the project is in the code widget below. Clicking the “Run” button executes the tests.
export default "test-file-stub";
Refactoring the previous code
Jest’s spyOn
function
The jest.spyOn
function allows a method in an object to be mocked. The syntax is:
jest.spyOn(object, methodName);
At first, this may not seem that useful for React apps consisting of functional code, but let’s go through the full example.
In the Hello.test.js
file within the test, output data
to the console. Add the following line at the start of the test: ...