Challenge: Using spyOn with getters

When you need to set the return value of functions in tests, such as returning dummy data to make the test easier to manage, then the recommended default way is to use spyOn (vi.spyOn() or jest.spyOn()).

For simple objects that contain a function, this is quite simple:

const spy = jest
  .spyOn(userService, 'getUser')
  .mockResolvedValue({
    id: 1,
    name: 'John Doe',
    email: 'john@example.com',
  });

However, what if you are trying to spyOn an object that uses getters (MDN ).

For example, how to spyOn something like the .latest getter property (which is actually implemented as a function)

const obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    return this.log[
      this.log.length - 1
    ];
  },
};

That is what this challenge is about!

When you need to spyOn a getter, there is a slightly different syntax.

Hint/Spoiler: The spyOn syntax for mocking a getter fn

You need to use a third argument when calling vi.spyOn(..) (or jest.spyOn). It should be 'get' for a getter.

That syntax is like this: vi.spyOn(user, 'name', 'get')

i
Challenge Mode: This lesson is actually a challenge - you are given a half working test and have to figure out how to get it working correctly.

You can use our courses to learn how to solve this challenge - there are courses on everything from basic Jest/Vitest fundamentals, down to how to test frontend code (using React Testing Library).

Loading full lesson content & code...

Ready to try running tests for this lesson?