]>
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 | }) | |
af37210c JM |
18 | } |
19 | ||
20 | collectEmails (emailsCollection: object[]) { | |
21 | return new Promise((res, rej) => { | |
22 | if (this.started) { | |
23 | this.emails = emailsCollection | |
24 | return res() | |
25 | } | |
26 | ||
27 | // ensure maildev isn't started until | |
28 | // unexpected exit can be reported to test runner | |
29 | this.emailChildProcess.send({ start: true }) | |
30 | this.emailChildProcess.on('exit', () => { | |
31 | return rej(new Error('maildev exited unexpectedly, confirm port not in use')) | |
32 | }) | |
33 | this.emailChildProcess.on('message', (msg) => { | |
34 | if (msg.err) { | |
35 | return rej(new Error(msg.err)) | |
36 | } | |
37 | this.started = true | |
38 | this.emails = emailsCollection | |
39 | return res() | |
40 | }) | |
41 | }) | |
42 | } | |
43 | ||
89ada4e2 C |
44 | kill () { |
45 | process.kill(this.emailChildProcess.pid) | |
46 | ||
47 | this.emailChildProcess = null | |
48 | MockSmtpServer.instance = null | |
49 | } | |
50 | ||
af37210c JM |
51 | static get Instance () { |
52 | return this.instance || (this.instance = new this()) | |
53 | } | |
f076daa7 C |
54 | } |
55 | ||
56 | // --------------------------------------------------------------------------- | |
57 | ||
58 | export { | |
af37210c | 59 | MockSmtpServer |
f076daa7 | 60 | } |