]>
Commit | Line | Data |
---|---|---|
89ada4e2 | 1 | import { fork, ChildProcess } from 'child_process' |
af37210c JM |
2 | |
3 | class MockSmtpServer { | |
4 | ||
5 | private static instance: MockSmtpServer | |
6 | private started = false | |
89ada4e2 | 7 | private emailChildProcess: ChildProcess |
af37210c JM |
8 | private emails: object[] |
9 | ||
10 | private constructor () { | |
89ada4e2 C |
11 | this.emailChildProcess = fork(`${__dirname}/email-child-process`, []) |
12 | ||
af37210c JM |
13 | this.emailChildProcess.on('message', (msg) => { |
14 | if (msg.email) { | |
15 | return this.emails.push(msg.email) | |
16 | } | |
17 | }) | |
a4101923 C |
18 | |
19 | process.on('exit', () => this.kill()) | |
af37210c JM |
20 | } |
21 | ||
22 | collectEmails (emailsCollection: object[]) { | |
23 | return new Promise((res, rej) => { | |
24 | if (this.started) { | |
25 | this.emails = emailsCollection | |
26 | return res() | |
27 | } | |
28 | ||
29 | // ensure maildev isn't started until | |
30 | // unexpected exit can be reported to test runner | |
31 | this.emailChildProcess.send({ start: true }) | |
32 | this.emailChildProcess.on('exit', () => { | |
33 | return rej(new Error('maildev exited unexpectedly, confirm port not in use')) | |
34 | }) | |
35 | this.emailChildProcess.on('message', (msg) => { | |
36 | if (msg.err) { | |
37 | return rej(new Error(msg.err)) | |
38 | } | |
39 | this.started = true | |
40 | this.emails = emailsCollection | |
41 | return res() | |
42 | }) | |
43 | }) | |
44 | } | |
45 | ||
89ada4e2 | 46 | kill () { |
a4101923 C |
47 | if (!this.emailChildProcess) return |
48 | ||
89ada4e2 C |
49 | process.kill(this.emailChildProcess.pid) |
50 | ||
51 | this.emailChildProcess = null | |
52 | MockSmtpServer.instance = null | |
53 | } | |
54 | ||
af37210c JM |
55 | static get Instance () { |
56 | return this.instance || (this.instance = new this()) | |
57 | } | |
f076daa7 C |
58 | } |
59 | ||
60 | // --------------------------------------------------------------------------- | |
61 | ||
62 | export { | |
af37210c | 63 | MockSmtpServer |
f076daa7 | 64 | } |