1 import { ChildProcess, fork } from 'child_process'
2 import { randomInt } from '../../core-utils/miscs/miscs'
3 import { parallelTests } from '../server/servers'
7 private static instance: MockSmtpServer
8 private started = false
9 private emailChildProcess: ChildProcess
10 private emails: object[]
12 private constructor () {
13 this.emailChildProcess = fork(`${__dirname}/email-child-process`, [])
15 this.emailChildProcess.on('message', (msg) => {
17 return this.emails.push(msg.email)
21 process.on('exit', () => this.kill())
24 collectEmails (emailsCollection: object[]) {
25 return new Promise<number>((res, rej) => {
26 const port = parallelTests() ? randomInt(1000, 2000) : 1025
29 this.emails = emailsCollection
33 // ensure maildev isn't started until
34 // unexpected exit can be reported to test runner
35 this.emailChildProcess.send({ start: true, port })
36 this.emailChildProcess.on('exit', () => {
37 return rej(new Error('maildev exited unexpectedly, confirm port not in use'))
39 this.emailChildProcess.on('message', (msg) => {
41 return rej(new Error(msg.err))
44 this.emails = emailsCollection
51 if (!this.emailChildProcess) return
53 process.kill(this.emailChildProcess.pid)
55 this.emailChildProcess = null
56 MockSmtpServer.instance = null
59 static get Instance () {
60 return this.instance || (this.instance = new this())
64 // ---------------------------------------------------------------------------