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 :
JavaScript
x
16
16
1
public async sentMail(params: ObjectLiteral) {
2
3
// Create the promise and SES service object
4
const sendPromise = new AWS.SES({ apiVersion: '2010-12-01' })
5
.sendEmail(params)
6
.promise();
7
8
// Handle promise's fulfilled/rejected states
9
sendPromise
10
.then(function (data) {
11
console.log(data.MessageId);
12
})
13
.catch(function (err) {
14
console.error(err, err.stack);
15
});
16
the test file is :
JavaScript
1
32
32
1
import SES from 'aws-sdk/clients/ses';
2
const mSES = {
3
sendEmail: jest.fn().mockReturnThis(),
4
promise: jest.fn().mockReturnThis(),
5
catch: jest.fn(),
6
};
7
jest.mock('aws-sdk/clients/ses', () => {
8
return jest.fn(() => mSES);
9
});
10
11
it('should send aws sesemail', async () => {
12
// const spy = jest.spyOn(AWS, 'SES');
13
const mSes = new SES() as unknown as {
14
sendEmail: jest.Mock;
15
promise: jest.Mock;
16
};
17
mSes
18
.sendEmail()
19
.promise.mockRejectedValueOnce(new Error('This is an SES error'));
20
const res = await sesMailService.sentMail(
21
{
22
toName: 'Name',
23
webUrl: 'webUrl',
24
},
25
);
26
expect(mSes.sendEmail).toBeCalledWith({
27
toName: 'Name',
28
webUrl: 'webUrl',
29
}
30
);
31
});
32
Its giving error message as:
JavaScript
1
6
1
TypeError: mSes.sendEmail( ).promise.mockRejectedValueOnce is not a function
2
3
94 | mSes
4
95 | .sendEmail()
5
> 96 | .promise.mockRejectedValueOnce(new Error('This is an SES error'));
6
Advertisement
Answer
Actually this mock works, the reason behind the error is that , i didn’t mocked the AWS.Credentials.
JavaScript
1
52
52
1
jest.mock('aws-sdk', () => {
2
3
return {
4
5
config: {
6
7
update() {
8
9
return {};
10
11
},
12
13
},
14
15
SES: jest.fn(() => {
16
17
return {
18
19
sendEmail: jest.fn((param) => {
20
21
return {
22
23
promise: () =>
24
25
new Promise((resolve, reject) => {
26
27
param?.Destination.ToAddresses[0] !== 'invalidmail@gmail.com'
28
29
? resolve({
30
31
MessageId: data.MessageId,
32
33
})
34
35
: reject(err);
36
37
}),
38
39
};
40
41
}),
42
43
};
44
45
}),
46
47
Credentials: jest.fn(),
48
49
};
50
51
});
52