Mocking function calls with Jest

colbygarland

Colby Garland

Posted on August 4, 2021

Mocking function calls with Jest

Imagine you have an API class, that you use to make all of your api calls with.

class API {
  login(username, password){ /* logic */ }
  logout(){ /* logic */ }
  getCurrentUser(){ /* logic */ }
}
Enter fullscreen mode Exit fullscreen mode

When we write automated tests using Jest (https://jestjs.io/) we want to "mock" these calls, since we don't want to be hitting the api each time we run our tests.

Luckily, Jest has this functionality for us, built-in :)

Let's create our mock function:

function mockLogin(){
  jest.spyOn(API, 'login').mockImplementation(() => {
    return {
      success: true
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Now in our test, we can mock this call before we make it:

it('user can login with correct username and password', () => {
  mockLogin();
  const api = new API();
  const response = api.login('colbygarland', 'hunter12');
  expect(response.success).toBe(true);
});
Enter fullscreen mode Exit fullscreen mode

You can rinse and repeat this for any API functions you want to mock - you can decide what data to return back, as if the api was actually sending it back :)

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
colbygarland
Colby Garland

Posted on August 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About