2021-06-14 16:52:22 +02:00
|
|
|
import { ChildProcess } from 'child_process'
|
2021-07-13 09:43:59 +02:00
|
|
|
import { randomInt } from '@shared/core-utils'
|
|
|
|
import { parallelTests } from '../miscs'
|
2018-12-15 14:51:51 +01:00
|
|
|
|
2021-06-14 16:52:22 +02:00
|
|
|
const MailDev = require('maildev')
|
|
|
|
|
2018-12-15 14:51:51 +01:00
|
|
|
class MockSmtpServer {
|
|
|
|
|
|
|
|
private static instance: MockSmtpServer
|
|
|
|
private started = false
|
2019-01-08 15:51:52 +01:00
|
|
|
private emailChildProcess: ChildProcess
|
2018-12-15 14:51:51 +01:00
|
|
|
private emails: object[]
|
|
|
|
|
2021-06-14 16:52:22 +02:00
|
|
|
private constructor () { }
|
2018-12-15 14:51:51 +01:00
|
|
|
|
|
|
|
collectEmails (emailsCollection: object[]) {
|
2019-04-24 15:10:37 +02:00
|
|
|
return new Promise<number>((res, rej) => {
|
|
|
|
const port = parallelTests() ? randomInt(1000, 2000) : 1025
|
2021-06-14 16:52:22 +02:00
|
|
|
this.emails = emailsCollection
|
2019-04-24 15:10:37 +02:00
|
|
|
|
2018-12-15 14:51:51 +01:00
|
|
|
if (this.started) {
|
2021-02-03 09:33:05 +01:00
|
|
|
return res(undefined)
|
2018-12-15 14:51:51 +01:00
|
|
|
}
|
|
|
|
|
2021-06-14 16:52:22 +02:00
|
|
|
const maildev = new MailDev({
|
|
|
|
ip: '127.0.0.1',
|
|
|
|
smtp: port,
|
|
|
|
disableWeb: true,
|
|
|
|
silent: true
|
|
|
|
})
|
|
|
|
|
|
|
|
maildev.on('new', email => {
|
|
|
|
this.emails.push(email)
|
2018-12-15 14:51:51 +01:00
|
|
|
})
|
2021-06-14 16:52:22 +02:00
|
|
|
|
|
|
|
maildev.listen(err => {
|
|
|
|
if (err) return rej(err)
|
2020-06-17 10:55:40 +02:00
|
|
|
|
2018-12-15 14:51:51 +01:00
|
|
|
this.started = true
|
2020-06-17 10:55:40 +02:00
|
|
|
|
2019-04-24 15:10:37 +02:00
|
|
|
return res(port)
|
2018-12-15 14:51:51 +01:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-01-08 15:51:52 +01:00
|
|
|
kill () {
|
2019-01-09 15:14:29 +01:00
|
|
|
if (!this.emailChildProcess) return
|
|
|
|
|
2019-01-08 15:51:52 +01:00
|
|
|
process.kill(this.emailChildProcess.pid)
|
|
|
|
|
|
|
|
this.emailChildProcess = null
|
|
|
|
MockSmtpServer.instance = null
|
|
|
|
}
|
|
|
|
|
2018-12-15 14:51:51 +01:00
|
|
|
static get Instance () {
|
|
|
|
return this.instance || (this.instance = new this())
|
|
|
|
}
|
2018-01-30 15:16:24 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
2018-12-15 14:51:51 +01:00
|
|
|
MockSmtpServer
|
2018-01-30 15:16:24 +01:00
|
|
|
}
|