Need to test AWS SES using jest unit testing But showing different errors, also tried solutions in another stackoverflow question The actual code to be tested is :
public async sentMail(params: ObjectLiteral) {
// Create the promise and SES service object
const sendPromise = new AWS.SES({ apiVersion: '2010-12-01' })
.sendEmail(params)
.promise();
// Handle promise's fulfilled/rejected states
sendPromise
.then(function (data) {
console.log(data.MessageId);
})
.catch(function (err) {
console.error(err, err.stack);
});
the test file is :
import SES from 'aws-sdk/clients/ses';
const mSES = {
sendEmail: jest.fn().mockReturnThis(),
promise: jest.fn().mockReturnThis(),
catch: jest.fn(),
};
jest.mock('aws-sdk/clients/ses', () => {
return jest.fn(() => mSES);
});
it('should send aws sesemail', async () => {
// const spy = jest.spyOn(AWS, 'SES');
const mSes = new SES() as unknown as {
sendEmail: jest.Mock;
promise: jest.Mock;
};
mSes
.sendEmail()
.promise.mockRejectedValueOnce(new Error('This is an SES error'));
const res = await sesMailService.sentMail(
{
toName: 'Name',
webUrl: 'webUrl',
},
);
expect(mSes.sendEmail).toBeCalledWith({
toName: 'Name',
webUrl: 'webUrl',
}
);
});
Its giving error message as:
TypeError: mSes.sendEmail(...).promise.mockRejectedValueOnce is not a function
94 | mSes
95 | .sendEmail()
> 96 | .promise.mockRejectedValueOnce(new Error('This is an SES error'));
CodePudding user response:
Actually this mock works, the reason behind the error is that , i didn't mocked the AWS.Credentials.
jest.mock('aws-sdk', () => {
return {
config: {
update() {
return {};
},
},
SES: jest.fn(() => {
return {
sendEmail: jest.fn((param) => {
return {
promise: () =>
new Promise((resolve, reject) => {
param?.Destination.ToAddresses[0] !== '[email protected]'
? resolve({
MessageId: data.MessageId,
})
: reject(err);
}),
};
}),
};
}),
Credentials: jest.fn(),
};
});