Nightwatch.js Tutorial: Getting Started with Test Automation
Set up Nightwatch.js, run your first browser test, and choose between local and remote execution, test types, and runners.
Nightwatch.js is a Node.js test automation framework that uses the W3C WebDriver API to control browsers. To get started, run its project initializer, choose a test type and execution environment, then run the generated example tests.
This tutorial follows the official quickstart path for a first local project. You can use JavaScript or TypeScript and configure other test types, browsers, runners, and remote execution as your needs grow. Nightwatch’s setup wizard chooses dependencies based on the testing type you select, so not every path uses the same configuration.
1. What Nightwatch.js does
Nightwatch is an integrated Node.js framework for automated end-to-end tests across major browsers. Its browser automation uses the W3C WebDriver standard. The official overview also describes testing Node.js services and HTTP APIs; the getting-started guide offers setup paths for component, mobile, visual regression, and accessibility testing.
WebDriver is the protocol layer: a browser driver implements the WebDriver API for its browser, and Nightwatch sends commands through that interface. The official overview lists Chrome, Firefox, Safari, and Edge, and also documents Selenium Server/Grid for distributed execution.
2. Check prerequisites and create a project
The Nightwatch quickstart lists Node.js as a prerequisite and says it supports versions above V14.20. Node and browser compatibility requirements can change, so check the current Getting Started guide before choosing a Node version for a new project.
To scaffold a new directory, run:
npm init nightwatch my-nightwatch-project
cd my-nightwatch-project
To start setup inside an existing project instead, run npm init nightwatch from that project’s directory. The initializer asks to install create-nightwatch, runs an interactive setup, writes a nightwatch.conf.js configuration based on your choices, and generates sample tests.
Choose setup options deliberately
The wizard asks about the kind of tests, language and runner, target browsers, test folder, base URL, and where tests should run. It also asks whether to enable anonymous metrics and may offer optional mobile-device setup. The documented defaults include a tests folder and http://localhost base URL.
| Choice | How to decide |
|---|---|
| Test type | Choose the path matching your work, such as end-to-end, component, mobile, API, visual regression, or accessibility. Dependencies and setup may differ by type. |
| Language and runner | Select JavaScript or TypeScript, then the Nightwatch runner, Mocha, or CucumberJS option offered for your path. |
| Browser | Start with the browser you can run locally, then add coverage for other target browsers. |
| Test folder | Use the default or select the directory your project already uses for test files. |
| Base URL | Set this to the application under test. The default http://localhost is only suitable if your app is served there. |
| Execution location | Local is simplest for a first run; remote grid or cloud needs endpoint settings and, for providers, account credentials. |
3. Run the generated sample
From the project directory, run the documented example command:
npx nightwatch ./nightwatch/examples
The CLI also accepts an individual test file or a folder. Its general form is npx nightwatch [source] [options]; source may identify one or more files or a directory. The quickstart shows an HTML report path under tests_output/nightwatch-html-report/index.html as example output. Report generation and exact output depend on the setup.
4. Add a first browser test
Nightwatch passes a browser API object to test scripts. The API reference notes that this object is also available globally starting with Nightwatch 2. A small test using the current browser style looks like this:
module.exports = {
'Example page has a title': async (browser) => {
await browser
.navigateTo('https://example.com')
.assert.titleContains('Example Domain')
.end();
}
};
Save it as a test file in the configured test folder, then pass that file to the CLI, for example npx nightwatch tests/example.js. This assumes your selected runner accepts the shown test-file style; if you chose Mocha or CucumberJS, follow that runner’s documented test structure and the sample generated by your setup.
Use your own application URL and stable selectors for application-specific checks. Keep test data deterministic where possible, and make each test responsible for setting up or identifying the state it needs.
5. Configure local Chrome
For a small local Chrome setup, Nightwatch’s environment guide installs Nightwatch and ChromeDriver from npm, configures environments under test_settings, and uses a required default environment as the inheritance base for named environments.
npm install --save-dev nightwatch chromedriver
A simplified configuration shape, based on the guide, is:
module.exports = {
src_folders: ['tests'],
test_settings: {
default: {
launch_url: 'http://localhost',
webdriver: {
start_process: true,
server_path: require('chromedriver').path,
port: 9515
}
},
chrome: {
desiredCapabilities: {
browserName: 'chrome'
}
}
}
};
This illustrates the documented configuration pattern; use the generated configuration and current Nightwatch environment guide as the source of truth for your installed version. Set launch_url to your app’s actual local address. Run a named environment with the CLI option documented for your version, commonly --env chrome.
6. Pick a test type, runner, and execution target
| Decision | Options | Good first choice |
|---|---|---|
| What to test | End-to-end, component, mobile, API, visual regression, accessibility; the overview also covers Node.js service and HTTP API tests. | Use end-to-end for a first browser workflow. Select another path when the system under test calls for it. |
| Language and runner | JavaScript or TypeScript; Nightwatch runner, Mocha, or CucumberJS. | Use a wizard-generated sample to learn the chosen runner’s structure before mixing styles. |
| Browser | Chrome, Firefox, Safari, Edge, depending on environment and driver availability. | Start with one browser, then expand coverage. |
| Where tests run | Local machine, Selenium Grid, or a cloud provider; local and remote can both be configured. | Run locally first. Add remote execution when you need provider-hosted machines, more browser coverage, or distributed runs. |
Local execution requires a compatible browser and driver setup. Remote execution requires a reachable Selenium server/grid or provider endpoint and the relevant settings. Nightwatch’s cloud guide gives BrowserStack and Sauce Labs examples; their credentials and services are not included with Nightwatch.
7. Run tests against a remote grid or cloud
Remote execution moves browser sessions to a Selenium Grid or provider-hosted machines. Configure the remote host and port plus provider-specific account credentials or keys under the environment settings. Keep secrets in environment variables or your CI secret store rather than committing them in the config file.
The exact keys differ by grid or cloud provider, so start from Nightwatch’s cloud provider guide and the provider’s current instructions. Confirm network access from the machine running Nightwatch, the correct remote endpoint, and the requested browser capabilities before running a suite.
8. Make tests more reliable
- Use selectors that represent stable app behavior instead of styling details likely to change.
- Wait for a meaningful page state or element before asserting; avoid fixed delays unless the application genuinely requires a known pause.
- Keep the base URL and environment-specific values in configuration so local, staging, and remote runs target the intended app.
- Make setup and cleanup explicit so test order does not affect results.
- When adding browsers or remote nodes, verify their driver and browser compatibility using current Nightwatch and provider documentation.
9. Troubleshooting
| Symptom | Likely cause | What to check |
|---|---|---|
npm init nightwatch cannot complete |
Node/npm is missing, unsupported by the current release, or package installation is blocked. | Check node --version and npm --version, compare Node with current Nightwatch installation guidance, and check registry or proxy access. |
| Browser session fails to start | Browser or driver is missing, incompatible, or configured at the wrong path/port. | Confirm the selected browser is installed, the driver dependency is installed, and the environment’s WebDriver settings match the local setup. |
| Connection refused to WebDriver | The driver or remote server did not start, the port is wrong, or the endpoint is unreachable. | Check process startup settings, host/port, firewall and network access, then inspect the driver or grid logs. |
| Test opens the wrong page | launch_url or the wizard’s base URL points elsewhere. |
Update the configured base URL and confirm which environment is selected for the run. |
| CLI reports no tests | The source path is wrong or does not match the configured test location. | Pass an existing file or folder to npx nightwatch and check the project’s test folder and file naming. |
| Test passes locally but fails remotely | Different browser versions, timing, network access, capabilities, or environment data. | Compare local and remote browser capabilities, verify the remote machine can reach the app, and wait for the same application state before assertions. |
| Unexpected test syntax or hook errors | The test file uses a structure for a different runner. | Check the selected runner and use its generated sample and matching Nightwatch guide. |
10. Performance, reliability, and cost
For a first project, one local browser keeps setup and diagnosis straightforward. Runtime and reliability depend on the application, browser, test design, and execution target; the supplied documentation does not establish universal speed or stability figures. Remote grids and cloud runs add network and provider configuration, but can provide access to remote browser environments and distributed execution.
Nightwatch is installed as Node.js software. The cited documentation does not specify a Nightwatch license price or the cost of remote provider services. Check the relevant provider’s current pricing before adopting cloud execution, and account for CI machine time and maintenance of browser/driver compatibility.
11. Capture screenshots during browser testing
Nightwatch tests can include browser automation, but teams sometimes need a separate way to capture clean page images for visual review, reports, or downstream processing. ScreenshotNeo is a website screenshot API and MCP server for developers. Its API takes a URL and returns PNG, JPEG, WebP, or PDF; the API documentation covers request options and setup.
Or skip the browser setup
Instead of configuring browser automation just to capture a page image, make one API request:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, with the outcome reflected in X-Page-Verdict and X-Billed headers. Its MCP server gives AI agents tools named take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots.
Sign up for 1,000 free screenshots a month, with no card required.
12. FAQ
Can I add TypeScript after choosing JavaScript?
The wizard supports JavaScript or TypeScript. Follow the current setup guide for changing a project’s language configuration and dependencies rather than mixing generated setups.
Does Nightwatch require Selenium Server for local tests?
The local Chrome guide shows Nightwatch with ChromeDriver. Selenium Server/Grid is a separate route for distributed or remote WebDriver execution.
Can I run just one test file?
Yes. The CLI accepts a file or folder as its source; use the path to the test you want to run.


