DEV Community

Colby Garland
Colby Garland

Posted on

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 :)

Discussion (0)