Nightwatch.js Deployment and Usage Guide
1. Prerequisites
- Node.js: Version 14.x or higher (Nightwatch v3 requires modern Node.js)
- npm or yarn: Package manager for Node.js
- Browser Drivers: ChromeDriver, GeckoDriver (Firefox), or SafariDriver for local browser testing
- Java: Required for Selenium Server (if not using direct ChromeDriver/GeckoDriver)
- Optional for Mobile Testing:
- Appium (v2.x recommended): For native mobile app testing
- Xcode: For iOS simulator/real device testing (macOS only)
- Android Studio/Android SDK: For Android emulator/real device testing
- Optional for Cloud Testing: BrowserStack, Sauce Labs, or other cloud grid accounts
2. Installation
Quick Setup (Recommended)
Initialize Nightwatch in an existing project or create a new one:
# Existing project
npm init nightwatch@latest
# New project
npm init nightwatch@latest ./path/to/new/project
The CLI will prompt you for:
- Language/Test Runner setup (JavaScript/TypeScript/Mocha)
- Test environment (Local, Remote, Cloud)
- Target browsers/devices
- Test file location
- Base URL for your application
Manual Installation
# Install Nightwatch as a dev dependency
npm install nightwatch --save-dev
# Install browser drivers
npm install chromedriver geckodriver --save-dev
# For TypeScript support
npm install typescript @types/node --save-dev
# For mobile testing
npm install appium --save-dev
Development/Contribution Setup
# Clone the repository
git clone https://github.com/nightwatchjs/nightwatch.git
cd nightwatch
# Install dependencies
npm install
# Run the test suite
npm test
# Check test coverage
npm run mocha-coverage
3. Configuration
Nightwatch supports three configuration file formats: nightwatch.conf.js, nightwatch.conf.cjs, or nightwatch.conf.ts (detected automatically).
Basic Configuration Structure
Create nightwatch.conf.js in your project root:
module.exports = {
// Source folders containing tests
src_folders: ['tests/specs'],
// Output folder for reports/screenshots
output_folder: 'tests/output',
// Page object definitions
page_objects_path: 'tests/page-objects',
// Custom commands/assertions
custom_commands_path: 'tests/custom-commands',
custom_assertions_path: 'tests/custom-assertions',
// Test globals
globals_path: 'tests/globals.js',
// Webdriver settings
webdriver: {
start_process: true,
server_path: require('chromedriver').path,
port: 9515
},
// Test environments
test_settings: {
default: {
launch_url: 'http://localhost:3000',
desiredCapabilities: {
browserName: 'chrome',
'goog:chromeOptions': {
w3c: true,
args: ['--headless', '--no-sandbox']
}
}
},
firefox: {
webdriver: {
server_path: require('geckodriver').path,
port: 4444
},
desiredCapabilities: {
browserName: 'firefox',
'moz:firefoxOptions': {
args: ['--headless']
}
}
},
// Mobile configuration (iOS)
ios: {
selenium: {
start_process: true,
server_path: require('appium').path,
port: 4723
},
desiredCapabilities: {
platformName: 'iOS',
platformVersion: '16.0',
deviceName: 'iPhone 14',
automationName: 'XCUITest',
app: '/path/to/your/app.app'
}
},
// Mobile configuration (Android)
android: {
selenium: {
start_process: true,
server_path: require('appium').path,
port: 4723
},
desiredCapabilities: {
platformName: 'Android',
platformVersion: '13.0',
deviceName: 'Android Emulator',
automationName: 'UiAutomator2',
app: '/path/to/your/app.apk'
}
},
// Cloud provider (BrowserStack)
browserstack: {
selenium: {
host: 'hub-cloud.browserstack.com',
port: 443
},
desiredCapabilities: {
'bstack:options': {
userName: '${BROWSERSTACK_USERNAME}',
accessKey: '${BROWSERSTACK_ACCESS_KEY}',
projectName: 'Nightwatch Project',
buildName: 'Build 1.0',
sessionName: 'E2E Tests'
},
browserName: 'chrome',
browserVersion: 'latest',
os: 'Windows',
osVersion: '11'
}
}
}
};
Environment Variables
Create a .env file for sensitive data (load via dotenv package):
# .env
BROWSERSTACK_USERNAME=your_username
BROWSERSTACK_ACCESS_KEY=your_access_key
SAUCE_USERNAME=your_sauce_username
SAUCE_ACCESS_KEY=your_sauce_access_key
Load in your config:
require('dotenv').config();
module.exports = {
test_settings: {
browserstack: {
desiredCapabilities: {
'bstack:options': {
userName: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
}
}
}
}
};
TypeScript Configuration
For TypeScript support, create nightwatch.conf.ts:
import {NightwatchOptions} from 'nightwatch';
const config: NightwatchOptions = {
src_folders: ['tests/specs'],
// ... rest of config
};
export default config;
4. Build & Run
Running Tests
# Run all tests in default environment (chrome)
npx nightwatch
# Run with specific environment
npx nightwatch --env firefox
npx nightwatch --env browserstack
# Run specific test file
npx nightwatch --test tests/specs/login.spec.js
# Run specific test case by name
npx nightwatch --testcase "should login successfully"
# Run with tags
npx nightwatch --tag smoke
npx nightwatch --skiptags slow
# Headless mode (already configured in capabilities)
npx nightwatch --headless
# Parallel execution
npx nightwatch --env chrome,firefox,safari --parallel
Component Testing
# React components
npm install @nightwatch/react --save-dev
# Vue components
npm install vite-plugin-nightwatch --save-dev
# Storybook integration
npm install @nightwatch/storybook --save-dev
Example component test configuration in nightwatch.conf.js:
module.exports = {
plugins: [
'@nightwatch/react',
'vite-plugin-nightwatch'
],
vite: {
start_vite: true,
port: 3000
}
};
Visual Regression Testing
Enable VRT in your test:
describe('Visual Regression', function() {
it('should compare screenshot', async function(browser) {
await browser
.url('http://example.com')
.assert.visualRegression();
});
});
Mobile App Testing
# Start Appium server (if not using automatic start)
appium --port 4723
# Run iOS tests
npx nightwatch --env ios
# Run Android tests
npx nightwatch --env android
Debugging
# Verbose logging
npx nightwatch --verbose
# Screenshot on failure (automatic)
npx nightwatch --screenshots
# Retain session on failure for debugging
npx nightwatch --pause-on-failure
# Chrome DevTools Protocol (CDP) debugging
npx nightwatch --devtools
5. Deployment (CI/CD Integration)
GitHub Actions
name: E2E Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
browser: [chrome, firefox]
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Install browser drivers
run: npx playwright install-deps chromium webkit
- name: Run Nightwatch tests
run: npx nightwatch --env ${{ matrix.browser }}
env:
BROWSERSTACK_USERNAME: ${{ secrets.BS_USER }}
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BS_KEY }}
- name: Upload test reports
if: always()
uses: actions/upload-artifact@v3
with:
name: test-reports
path: tests/output/
Docker Deployment
Create Dockerfile:
FROM node:18-alpine
WORKDIR /app
# Install Chrome and dependencies for headless testing
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont
ENV CHROME_BIN=/usr/bin/chromium-browser
COPY package*.json ./
RUN npm ci
COPY . .
CMD ["npx", "nightwatch", "--env", "chrome"]
Run with Docker Compose:
version: '3'
services:
nightwatch:
build: .
volumes:
- ./tests/output:/app/tests/output
environment:
- BROWSERSTACK_USERNAME=${BROWSERSTACK_USERNAME}
- BROWSERSTACK_ACCESS_KEY=${BROWSERSTACK_ACCESS_KEY}
network_mode: host
Cloud Grid Configuration
BrowserStack:
// nightwatch.conf.js
test_settings: {
browserstack: {
selenium: {
host: 'hub-cloud.browserstack.com',
port: 443
},
desiredCapabilities: {
'bstack:options': {
userName: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY,
projectName: 'Production Tests',
buildName: process.env.GITHUB_SHA || 'local-build',
sessionName: 'Nightwatch E2E',
debug: true,
networkLogs: true
},
browserName: 'chrome'
}
}
}
Sauce Labs:
saucelabs: {
selenium: {
host: 'ondemand.saucelabs.com',
port: 443
},
desiredCapabilities: {
'sauce:options': {
username: process.env.SAUCE_USERNAME,
accessKey: process.env.SAUCE_ACCESS_KEY
}
}
}
Parallel Execution in CI
# Run tests across multiple environments in parallel
npx nightwatch --env chrome,firefox,edge,safari --parallel --workers 4
6. Troubleshooting
Configuration Issues
Error: "No config file found"
- Nightwatch automatically creates
nightwatch.conf.jsif missing when usingnpm init nightwatch@latest - For manual setup, ensure the config file is in the working directory where you run the command
- Supports
.js,.cjs, or.tsextensions
Error: "WebDriverError: chrome not reachable"
- Ensure ChromeDriver version matches your Chrome browser version
- Update via:
npm install chromedriver@latest --save-dev - For CI, use
--headlessand--no-sandboxflags in chromeOptions
Mobile Testing Issues
Error: "RealIosDeviceIdError" or "Could not find device"
- Verify Xcode is installed and command line tools are configured:
xcode-select --install - For real iOS devices, ensure the device UDID is correctly specified in capabilities
- Check Appium is installed:
npm install -g appiumornpm install appium --save-dev
Error: "Appium session could not be created"
- Ensure the app path is absolute, not relative
- For Android, verify SDK is installed and
ANDROID_HOMEis set - Check that the app file (.app for iOS, .apk for Android) exists at the specified path
Test Execution Issues
Flaky tests / Timeout errors
- Increase
globals.waitForConditionTimeoutin config (default is often 5s) - Add explicit waits:
await browser.pause(1000)orawait browser.waitForElementVisible('selector') - Use
browser.globals.abortOnAssertionFailure = falsefor soft assertions
Screenshot comparison failures (Visual Regression)
- Ensure baseline images are committed to your repo or generated in CI
- Run locally with
--update-baselinesflag to update references - Check for OS-specific rendering differences (fonts, anti-aliasing)
Element not found errors
- Verify selectors are correct and unique
- Check if the element is inside an iframe:
browser.frame('iframeName') - For Shadow DOM elements, use
browser.shadowRoot()orgetShadowElement()
Debug Mode
Enable detailed logging to diagnose issues:
# Maximum verbosity
npx nightwatch --verbose --debug
# Keep browser open on failure
npx nightwatch --pause-on-failure
# View raw WebDriver commands
DEBUG=nightwatch:* npx nightwatch
Common Exit Codes
0: All tests passed1: Test failures or errors5: Configuration error (missing config file)10: Webdriver server not reachable11: Test timeout exceeded