Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking:
async cognitoRegister(userPool: CognitoUserPool, {
name,
password,
email
}: AuthRegisterInput): Promise < ISignUpResult > {
return new Promise((resolve, reject) => {
return userPool.signUp(
name,
password,
[new CognitoUserAttribute({
Name: 'email',
Value: email
})],
null,
(err, result) => {
if (!result) {
reject(err);
} else {
resolve(result);
}
},
);
});
}
The signUp function is from the third-party CognitoUserPool which was successfully mocked using module name mapper in my package.json as shown below:
function CognitoUserPool(data) {
const { UserPoolId, ClientId } = data;
this.userPoolId = UserPoolId;
this.clientId = ClientId;
this.getCurrentUser = jest.fn().mockReturnValue("cognitouserpool");
// This method
this.signUp = jest.fn().mockReturnValue(true);
}
module.exports = CognitoUserPool;
Its implementation:
module.exports = {
CognitoUserPool: jest.fn().mockImplementation(require("./CognitoUserPool")),
};
Since signUp method accepts a callback to provide a result or rejection value, mocking it is essential to prevent Jest timeout errors due to the pending Promise.
I am essentially trying to mock a function like so:
const foo = (arg1, cb) => {
...do something...
}
const bar = (arg1, arg2...) => {
return new Promise((resolve, reject) => {
return foo(arg1, (err, result) => {
if (!result) {
reject(err)
} else {
resolve(result)
}
})
})
}
This is what I am attempting in my test:
it("should register a cognito user", async () => {
const mockedCongitoUserPool = new CognitoUserPool({
UserPoolId: authConfig.userPoolId,
ClientId: authConfig.clientId,
});
const result = await service.cognitoRegister(mockedCongitoUserPool, {
...mockedUser,
});
console.log(result);
});
For more details, refer to these git links:
Mocked third party implementation link
Your assistance is greatly appreciated! Feel free to ask for further clarification, as I could really use some help with this. <3