Mocking function calls with Jest
Colby Garland
Posted on August 4, 2021
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 */ }
}
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
}
}
}
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);
});
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 :)
๐ ๐ช ๐
๐ฉ
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
jest Testing LLM Applications: Misadventures in Mocking SDKs vs Direct HTTP Requests
November 11, 2024