This project provides support for easy integration/acceptance testing of nginx configuration using TypeScript or JavaScript, primarily for testing njs (NGINX JavaScript) scripts.
It allows you to run tests against various nginx versions on any Linux, macOS or Windows (x64) system without need to install nginx or use some overcomplex methods such as Docker [1]. nginx-testing automatically downloads a precompiled nginx binary for your system and architecture from project nginx-binaries.
# using npm:
npm install --save-dev nginx-testing
# or using yarn:
yarn add --dev nginx-testingimport { strict as assert } from 'assert'
import { after, afterEach, before, beforeEach, test } from 'mocha'
import { startNginx, NginxServer } from 'nginx-testing'
import fetch from 'node-fetch'
let nginx: NginxServer
before(async () => {
nginx = await startNginx({ version: '1.24.x', configPath: './nginx.conf' })
})
after(async () => {
await nginx.stop()
})
beforeEach(async () => {
// Consume logs (i.e. clean them before the test).
await nginx.readAccessLog()
await nginx.readErrorLog()
})
afterEach(async function () {
// Print logs if the test failed.
if (this.currentTest?.state === 'failed') {
console.error('Access log:\n' + await nginx.readAccessLog())
console.error('Error log:\n' + await nginx.readErrorLog())
}
})
test('GET / results in HTTP 200', async () => {
const resp = await fetch(`http://localhost:${nginx.port}/`)
assert.equal(resp.status, 200)
})events {
}
http {
server {
listen localhost:__PORT__;
location / {
return 200 "OK";
}
}
}- startNginx
(opts: NginxOptions) ⇒ Promise<NginxServer> -
Starts nginx server with the given configuration.
Example:import { startNginx, NginxServer } from 'nginx-testing' import fetch from 'node-fetch' let nginx: NginxServer before(async () => { nginx = await startNginx({ version: '1.24.x', configPath: './nginx.conf' }) }) after(nginx.stop) test('GET / results in HTTP 200', async () => { const resp = await fetch(`http://localhost:${nginx.port}/`) assert(resp.status === 200) })
- nginxVersionInfo
(nginxBinPath: string) ⇒ Promise<NginxVersionInfo> -
Executes the nginx binary
nginxBinPathwith option-Vand returns parsed version and info about the modules it was compiled with(out). - parseConf
(source: string) ⇒ NginxConfEditor -
Parses the given nginx config.
- setLogger
(logger: object) ⇒ void -
Use the given logger — an object with functions
debug,info,warn, anderror. Undefined logging functions will be replaced with no-op.See section Logging for more information.
Options for startNginx().
- binPath
(?string) -
Name or path of the nginx binary to start. Defaults to
'nginx'.This option is ignored if
versionis provided. - version
(?string) -
A SemVer version range specifying the nginx version to run.
Nginx binary for your OS and architecture will be downloaded from nginx-binaries. It will be stored in directory
.cache/nginx-binaries/inside the nearest writeablenode_modulesdirectory or innginx-binaries/inside the system-preferred temp directory.Not all versions are available. You can find a list of available binaries at nginx-binaries.
- config
(?string) -
Nginx configuration to use.
If
configPathis provided, the processed config will be written to a temporary file.<filename>~(where<filename>is a filename fromconfigPath) in theconfigPath’s directory (e.g.conf/nginx.conf→conf/.nginx.conf~). Otherwise it will be written intonginx.conffile inworkDir. In either case, this file will be automatically deleted after stopping the nginx.The config may include the following placeholders which will be replaced with corresponding values:
-
__ADDRESS__— The address as specified inbindAddress. -
__CONFDIR__— Path to directory with the config file as specified inconfigPath. -
__CWD__— The current working directory as reported byprocess.cwd(). -
__WORKDIR__— Path to the nginx’s working directory as specified inworkDir. -
__PORT__,__PORT_1__, …,__PORT_9__— The port numbers as specified inportsandpreferredPorts.
It will be modified for compatibility with the runner by applying patch operations specified in
configPatchvariable.Either
configPath, orconfigmust be provided! -
- configPath
(?string) -
Path of the nginx configuration file to use.
This file will be processed and the resulting config file will be written to a temporary file
.<filename>~(where<filename>is a filename fromconfigPath) in theconfigPath’s directory (e.g.conf/nginx.conf→conf/.nginx.conf~). This temporary file will be automatically deleted after stopping the nginx.See
configoption for information about placeholders and patching.Either
configPath, orconfigmust be provided! - bindAddress
(?string) -
Hostname or IP address the port(s) will be binding on. This is used when searching for free ports (see
preferredPorts) and for substituting__ADDRESS__placeholder in the given nginx config. Defaults to'127.0.0.1'. - ports
(?number[]) -
A list of port numbers for substituting
__PORT__,__PORT_1__, …,__PORT_9__placeholders in the given nginx config. UnlikepreferredPorts, these are not checked for availability and nginx will fail to start if any of the provided and used ports is unavailable.If it’s not provided or more ports are needed, next ports are selected from the
preferredPortsor randomly. - preferredPorts
(?number[]) -
A list of preferred port numbers to use for substituting
__PORT__,__PORT_1__, …,__PORT_9__placeholders in the given nginx config.Unavailable ports (used by some other program or restricted by OS) are skipped. If there are no preferred ports left and another port is needed, a random port number is used.
- workDir
(?string) -
Path of a directory that will be passed as a prefix (
-p) intonginx. It will be automatically created if doesn’t exist.If not provided, an unique temporary directory will be created:
.cache/nginx-testing-XXXXXX/relative to the nearest writablenode_modules(nearest toprocess.cwd()) ornginx-testing-XXXXXX/in the system-preferred temp directory. The created directory will be automatically deleted after stopping. - errorLog
(?string | ?stream.Writable) -
One of:
-
'buffer'— Collect the nginx’s stderr to a buffer that can be read usingreadErrorLog()(default). -
'ignore'— Ignore nginx’s stderr. -
'inherit'— Pass through the nginx’s stderr output to the Node process. -
<stream.Writable>— A writable stream to pipe the nginx’s stderr to.
Nginx error log is expected to be redirected to stderr. Directive
error_log stderr info;will be automatically added to the config, unless there’s alreadyerror_logdefined in the main context. -
- accessLog
(?string | ?stream.Writable) -
One of:
-
'buffer'— Collect the nginx’s access log to a buffer that can be read usingreadAccessLog()(default). -
'ignore'— Ignore nginx’s access log. -
<stream.Writable>— A writable stream to pipe the nginx’s access log to.
Nginx access log is expected to be redirected to file
<workDir>/access.log. Directiveaccess_log access.log;will be automatically added to the config, unless there’s alreadyaccess_logdefined in thehttpcontext. -
- startTimeoutMsec
(?number) -
Number of milliseconds after the start to wait for the nginx to respond to the health-check request (
HEAD http://<bindAddress>:<ports[0]>/health). Any HTTP status is considered as success — it just checks if the nginx is listening and responding.Defaults to
1000.
- config
(?string) -
The same as in NginxOptions.
- configPath
(?string) -
The same as in NginxOptions.
A return value of startNginx().
- config
(string) -
The current nginx configuration.
- pid
(number) -
PID of the nginx process.
- port
(number) -
Number of the first port allocated for nginx, i.e. the port on which nginx should listen for connections. It’s the same as
ports[0]. - ports
(number[]) -
A list of port numbers allocated for nginx.
- workDir
(string) -
Path of the nginx’s working directory.
- readAccessLog
() ⇒ Promise<string> -
Reads new messages from the access log since the last call of
readAccessLog().Throws
Errorif the process was created with optionaccessLogother than'buffer'orundefined. - readErrorLog
() ⇒ Promise<string> -
Reads new messages from the error log since the last call of
readErrorLog().Throws
Errorif the process was created with optionerrorLogother than'buffer'orundefined. - reload
(?RestartOptions) ⇒ Promise<void> -
Reloads the nginx (using SIGHUP), optionally with a new configuration. Options
configandconfigPathare mutually exclusive here.Nginx can be reloaded only when running with the master process. This is disabled by default, but you can override it by declaring
master_process onin the config.Important: The function you are looking for is
restart(). Usereload()only if you know that you cannot userestart().Caution: This function doesn’t work on Windows!
Throws
Errorif nginx was started withmaster_process offor if running on Windows (win32platform). - restart
(?RestartOptions) ⇒ Promise<void> -
Restarts the nginx, optionally with a new configuration. Options
configandconfigPathare mutually exclusive here. The new nginx process will be started with the same ports, working directory etc. - stop
() ⇒ Promise<void> -
Stops the nginx and cleans-up temporary files and directories.
Parsed output of nginx -V returned by nginxVersionInfo().
- version
(string) -
Nginx version number (e.g.
'1.24.0'). - modules
(Object.<string, string>) -
An object of module names as properties with value
'with','with-dynamic', or'without'.Example:{ http_fastcgi: 'without', http_geoip: 'with-dynamic', http_ssl: 'with', }
Nginx configuration editor returned by parseConf().
- get
(path: string) ⇒ string | string[] | undefined -
Returns a value of a directive at the path specified by a JSON Pointer (e.g.
/http/servers/0/listen).-
If the directive is not declared, returns
undefined. -
If the path points to an unnamed block (e.g.
server), returns an empty string. -
If an intermediate directive is declared multiple times and no index is specified in the path (e.g.
/http/servers/listen), the first one is selected (/http/servers/0/listen). -
If the path points to a directive that is declared multiple times (in the same context), returns an array of each declaration’s value.
-
- applyPatch
(patch: PatchOperation[]) ⇒ this -
Applies the specified patch operations on the config.
Throws
RangeErrorif some intermediate directive on the path does not exist. - toString
() ⇒ string -
Dumps the config back to string.
A patch operation to be performed on nginx config.
It’s an object with the following properties:
- op
(string) -
The operation name; one of:
-
'add'— Adds a directive. -
'default'— Sets a directive if it’s not declared yet. -
'remove'— Removes a directive. -
'set'— Sets a directive and removes its existing declarations in the same context.
-
- path
(string) -
A JSON Pointer of the directive to be added, set or removed.
For example,
/http/server/1/listenpoints to a directivelistenin the secondservercontext insidehttpcontext. See documentation ofgetfunction in NginxConfEditor for more information. - value
(string) -
A value of the directive (not defined for op
'remove').
This is based on JSON Patch, but with a different operations.
-
If anylogger is available and initialized (any adapter has been registered), then:
-
all log messages will go through
anyloggerloggernginx-binaries.
-
-
If debug is available, then:
-
debug messages will be logged via
debugloggernginx-binaries, others (error, warn, info) viaconsole.
-
-
otherwise:
-
error, warn, and info messages will be logged via
console, debug messages will be discarded.
-
If none of these options is suitable, you can provide your own logger using setLogger():
import { setLogger } from 'nginx-testing'
setLogger({
warn: console.warn,
error: console.error,
// undefined logging functions will be replaced with no-op
})start-nginx [options] <conf-file> start-nginx -h | --help
Start nginx server with the given config and reload it on changes.
- -b --bin-path <file>
-
Name or path of the nginx binary to start. Defaults to
nginx. This option is ignored if --version is specified. - -v --version <semver>
-
A SemVer version range specifying the nginx version to download from nginx-binaries a and run.
- -A --bind-address <host>
-
Hostname or IP address to bind the port(s) on. Defaults to 127.0.0.1.
- -p --port <port>
-
Port number(s) for substituting
__PORT__,__PORT_1__, …,__PORT_9__placeholders in the nginx config. Repeat this option for more ports. Defaults to random port numbers. - -d --work-dir <dir>
-
Path of a directory that will be passed as a prefix into nginx. If not provided, a temporary directory will be automatically created.
- -T --start-timeout <msec>
-
Number of milliseconds after the start to wait for the nginx to respond to the health-check request. Defaults to 1,000 ms.
- -w --watch <path>
-
Watch file or directory (recursively) and reload nginx on changes. <conf-file> is watched implicitly. Repeat this option for more paths.
- -D --watch-delay <msec>
-
Delay time between reloads in milliseconds. Defaults to 200 ms.
- -h --help
-
Show help message and exit.
This project is licensed under MIT License.