JEST: React Testing Library
SPY on a class constructor using Jest
Today, I would like to document and share with the community a few tips on testing.
As a developer working for a company with a large engineering team divided into sub-teams or squads where every member is working on the same project or code base but different features, having to test your work before merging is a high priority.
And so, I have been pretty involved in writing unit tests for my lines of code recently.
I had worked on a bug on the Login component and needed to mock CognitoUser for the unit test.
CognitoUser is a constructor class, and I need to spy on it.
firstly I import with an alias from amazon-cognito-identity-js
import * as CognitoClasses from 'amazon-cognito-identity-js';
then in my assertion, create a constcognitoUserSpy
as in the code below, and notice how I had to mock return values for setAuthenticationFlowType
and authenticateUser
.
const cognitoUserSpy = jest
.spyOn(CognitoClasses, 'CognitoUser')
.mockReturnValue({
setAuthenticationFlowType: () => {},
authenticateUser: () => {}
});
// write your expect here
// expect()
// restore/clear all mocks
Finally, don’t forget to restore the mock created with jest.spyOn
, else it causes memory leak. You can do this inside the afterEach(() => {})
or after your assert or expect method.
cognitoUserSpy.mockRestore();
Thanks.