How to setup tests in Nodejs project?
- Use a
./test
folder in the project root to hold all tests
- Install and use esm to support
import
syntax in Nodejs for cleaner code
- For integration test, install dependencies like better-sqlite3 and node-sqlite3 to test database interactions
- Tests can use helper functions from
./test/support/helper.js
- Organize tests by feature in separate files, like
./test/featureA.test.js
How to write integration tests using databases in Nodejs?
- Use an in-memory database like
better-sqlite3
to avoid test polution
- Write helper functions to setup and seed the in-memory database for each test module
- Use
beforeEach
and afterEach
to setup/cleanup database for each test case
How to test CLI commands in Nodejs?
- Put each command test case in a separate subfolder under
./test
- Each subfolder contains:
cmd
- The CLI command to run
input
- Input passed to the CLI
expected.stdout
- Expected standard output
expected.stderr
- Expected standard error
- Use
child_process.exec
in test file to execute the cmd
- Assert
exitCode
, stdout
, stderr
with expected values
// Execute CLI command
var exec = require('child_process').exec;
exec('bash cmd', {cwd: dir}, function(error, stdout, stderr) {
// Assert exitCode, stdout, stderr
});
How to turn JS code using require
to import
for tests?
- Use esm to transpile
import
syntax on the fly
- Alternative is to use babel to transpile entire test codebase
- Keep production codebase untouched to avoid breaking changes
// Install esm
npm install --save-dev esm
// Use esm to run tests
npm test -- --require esm
ref: