Skip to content

Commit c3b6b17

Browse files
committed
feat: use random port for testing
1 parent ab68e65 commit c3b6b17

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/EnvParser/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,14 @@ export class EnvParser {
1919

2020
private parser = new Parser(false)
2121

22+
constructor(private envFileName: string = '.env') {}
23+
2224
/**
2325
* Parse .env file contents
2426
*/
2527
public async parse(rootDir: string) {
2628
try {
27-
this.envContents = this.parser.parse(await readFile(join(rootDir, '.env'), 'utf-8'))
29+
this.envContents = this.parser.parse(await readFile(join(rootDir, this.envFileName), 'utf-8'))
2830
} catch {}
2931
}
3032

src/Test/index.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import { TestProcess } from './process'
1919
import { JapaFlags } from '../Contracts'
2020

2121
import { ENV_FILES, TESTS_ENTRY_FILE } from '../../config/paths'
22+
import { EnvParser } from '../EnvParser'
23+
import getPort from 'get-port'
2224

2325
/**
2426
* Exposes the API to watch project for compilition changes and
@@ -115,6 +117,30 @@ export class TestsServer {
115117
process.exit()
116118
}
117119

120+
/**
121+
* Returns the HOST and the PORT environment variables
122+
* for the HTTP server
123+
*/
124+
private async getEnvironmentVariables() {
125+
const envParser = new EnvParser('.env.test')
126+
await envParser.parse(this.appRoot)
127+
128+
const envOptions = envParser.asEnvObject(['PORT', 'TZ', 'HOST'])
129+
const HOST = process.env.HOST || envOptions.HOST || '0.0.0.0'
130+
let PORT = Number(process.env.PORT || envOptions.PORT)
131+
132+
/**
133+
* Use the port defined inside ".env.test" file or use
134+
* a random port
135+
*/
136+
PORT = await getPort({
137+
port: !isNaN(PORT) ? [PORT] : [],
138+
host: HOST,
139+
})
140+
141+
return { HOST, PORT: String(PORT) }
142+
}
143+
118144
/**
119145
* Run tests. Use [[watch]] to also watch for file
120146
* changes
@@ -141,7 +167,7 @@ export class TestsServer {
141167
filters,
142168
this.nodeArgs,
143169
this.logger,
144-
{}
170+
await this.getEnvironmentVariables()
145171
).run()
146172

147173
this.busy = false

0 commit comments

Comments
 (0)