This repository has been archived by the owner on Feb 10, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
EmailServiceImpl.test.ts
95 lines (76 loc) · 2.76 KB
/
EmailServiceImpl.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright (c) 2023. Heusala Group Oy <info@hg.fi>. All rights reserved.
import { createTransport } from 'nodemailer';
import { EmailMessage } from "../core/email/types/EmailMessage";
import { LogLevel } from "../core/types/LogLevel";
import { EmailServiceImpl } from "./EmailServiceImpl";
const mockTransporter = {
sendMail: jest.fn()
};
jest.mock('nodemailer', () => ({
createTransport: jest.fn()
}));
beforeAll(() => {
EmailServiceImpl.setLogLevel(LogLevel.NONE);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('EmailServiceImpl', () => {
let service: EmailServiceImpl;
const defaultFrom = 'default@from.com';
beforeEach(() => {
service = EmailServiceImpl.create(defaultFrom);
(createTransport as any).mockReturnValue(mockTransporter);
});
describe('setDefaultFrom', () => {
it('should set default from address', () => {
const from = 'test@from.com';
service.setDefaultFrom(from);
expect(service['_from']).toEqual(from);
});
});
describe('initialize', () => {
it('should create transporter with localhost and port 25 if config is empty', () => {
service.initialize('');
expect(createTransport).toHaveBeenCalledTimes(1);
expect(createTransport).toHaveBeenCalledWith({
host: 'localhost',
port: 25,
secure: false,
});
});
// More tests for different configs would be written here
});
describe('sendEmailMessage', () => {
const message: EmailMessage = {
to: 'test@to.com',
subject: 'Test Subject',
content: 'Test Content',
};
beforeEach(() => {
service.initialize('');
expect(createTransport).toHaveBeenCalledTimes(1);
expect(createTransport).toHaveBeenCalledWith({
host: 'localhost',
port: 25,
secure: false,
});
});
it('should throw error if from address is not set', async () => {
service['_from'] = '';
await expect(service.sendEmailMessage(message)).rejects.toThrow('"from" must be defined');
});
it('should send email using transporter', async () => {
await service.sendEmailMessage(message);
expect(mockTransporter.sendMail).toHaveBeenCalledTimes(1);
expect(mockTransporter.sendMail).toHaveBeenCalledWith({
from: defaultFrom,
to: message.to,
subject: message.subject,
text: message.content,
html: message.content,
});
});
// More tests for different scenarios would be written here
});
});