Issue
I am writing a jest test where I want to mock a service to return an object of the correct type according to its interface. The type of object to be returned has a complicated constructor that would require a lot of work to create and keep typescript happy. What is the best/easiest way to achieve this (code sample below)
import Auth, { CognitoUser } from '@aws-amplify/auth';
jest.mock('@aws-amplify/auth');
const mockedAuth = Auth as jest.Mocked<typeof Auth>;
const loggedInUser = new CognitoUser(); \\ Expected 1 arguments, but got 0.
mockedAuth.signIn.mockResolvedValue(loggedInUser);
In the above code the test will run and create an instance of CognitoUser with all the functions stubbed out, but TypeScript complains that I am not passing the required parameters. Is there a way I can make it happy without adding @ts-ignore?
Note: the parameter the constructor is expecting is of type ICognitoUserData, which itself has required fields that would go many levels deep.
Solution
For anyone else who comes across this question and wants the answer, the best I could get was:
const loggedInUser = new CognitoUser({} as ICognitoUserData);
Seems perfectly acceptable to just cast objects to the desired types within tests.
Answered By - DaveJohnston
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.