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 :)
Top comments (0)