Welcome to the SmartUI SDK sample for Selenium JavaScript. This repository demonstrates how to integrate SmartUI visual regression testing with Selenium JavaScript.
smartui-node-sample/
├── sdk/
│ ├── sdkCloud.js # Cloud test
│ ├── sdkLocal.js # Local test
│ └── smartui-web.json # SmartUI config (create with npx smartui config:create)
└── hooks/ # Hooks integration examples
└── examples/ # Hooks examples
- Node.js installed
- LambdaTest account credentials (for Cloud tests)
- Chrome browser (for Local tests)
For Cloud:
export LT_USERNAME='your_username'
export LT_ACCESS_KEY='your_access_key'
export PROJECT_TOKEN='your_project_token'For Local:
export PROJECT_TOKEN='your_project_token'git clone https://github.com/LambdaTest/smartui-node-sample
cd smartui-node-sample/sdkInstall the required dependencies:
npm i @lambdatest/smartui-cli @lambdatest/selenium-driver selenium-webdriverDependencies included:
@lambdatest/smartui-cli- SmartUI CLI@lambdatest/selenium-driver- SmartUI SDK for Selenium JavaScriptselenium-webdriver- Selenium WebDriver
Note: To ensure seamless execution of ES6 modules, add "type": "module" to your package.json file.
npx smartui config:create smartui-web.jsonThe SmartUI screenshot function is already implemented in the repository.
Cloud Test (sdk/sdkCloud.js):
import { smartuiSnapshot } from '@lambdatest/selenium-driver';
await driver.get('https://www.lambdatest.com');
await smartuiSnapshot(driver, "screenshot");Local Test (sdk/sdkLocal.js):
import { smartuiSnapshot } from '@lambdatest/selenium-driver';
await driver.get('https://www.lambdatest.com');
await smartuiSnapshot(driver, "screenshot");Note: The code is already configured and ready to use. You can modify the URL and screenshot name if needed.
npx smartui exec node sdkLocal.jsnpx smartui exec node sdkCloud.jsThis repository also includes examples for using SmartUI with LambdaTest Hooks integration. Hooks-based integration allows you to use SmartUI directly within your existing LambdaTest Cloud automation tests without requiring the SmartUI CLI.
SDK Approach (Recommended for Local Testing):
- âś… Works with both local and cloud execution
- âś… Uses SmartUI CLI for configuration and execution
- âś… Supports multiple browsers and viewports via
smartui-web.json - âś… Better for CI/CD integration
- âś… Requires
PROJECT_TOKENenvironment variable
Hooks Approach (Recommended for Cloud-Only Testing):
- âś… Works only with LambdaTest Cloud Grid
- âś… No CLI required - direct integration with LambdaTest
- âś… Uses LambdaTest capabilities for configuration
- âś… Better for existing LambdaTest automation suites
- âś… Requires
LT_USERNAMEandLT_ACCESS_KEYenvironment variables
Location: See the hooks folder, where you can see all the examples scripts to setup your suite or run the demo.
Purpose: Enhance visual regression capabilities in your LambdaTest web automation tests running on LambdaTest Cloud Grid.
Documentation: LambdaTest Selenium Visual Regression Documentation.
Navigate to the hooks directory and install dependencies:
cd hooks
npm i selenium-webdriverSet your LambdaTest credentials:
export LT_USERNAME='your_username'
export LT_ACCESS_KEY='your_access_key'In your test file (e.g., hooks/examples/test.js), configure the capabilities with SmartUI options:
const USERNAME = process.env.LT_USERNAME;
const KEY = process.env.LT_ACCESS_KEY;
let capabilities = {
platform: "Windows 10",
browserName: "chrome",
version: "latest",
visual: true, // Enable visual testing
"user": USERNAME,
"accessKey": KEY,
name: "test session",
build: "Automation Build",
"LT:Options": {
"smartUI.project": "<Your Project Name>", // Your SmartUI project name
"smartUI.build": "<Your Build Name>", // Optional: Build name
"smartUI.baseline": false, // Set to true to update baseline
"smartUI.options": {
"output": {
"errorColor": { "red": 200, "green": 0, "blue": 255 },
"errorType": "movement",
"transparency": 0.3,
"largeImageThreshold": 100,
"useCrossOrigin": false,
"outputDiff": true
},
"scaleToSameSize": true,
"ignore": "antialiasing"
}
}
};Create a WebDriver instance connected to LambdaTest Cloud:
const GRID_HOST = "@hub.lambdatest.com/wd/hub";
const gridUrl = `https://${USERNAME}:${KEY}${GRID_HOST}`;
const driver = await new webdriver.Builder()
.usingServer(gridUrl)
.withCapabilities(capabilities)
.build();Use driver.executeScript() to capture screenshots at any point in your test:
// Navigate to your page
await driver.get('https://www.lambdatest.com');
// Take a screenshot with basic configuration
let config = {
screenshotName: 'homepage-screenshot'
};
await driver.executeScript("smartui.takeScreenshot", config);
// Take a full-page screenshot
let fullPageConfig = {
screenshotName: 'homepage-full-page',
fullPage: true
};
await driver.executeScript("smartui.takeScreenshot", fullPageConfig);
// Take a screenshot with custom options
let customConfig = {
screenshotName: 'homepage-custom',
fullPage: true,
ignore: ["antialiasing", "colors"],
boundingBoxes: [{ x: 100, y: 100, width: 200, height: 200 }]
};
await driver.executeScript("smartui.takeScreenshot", customConfig);Execute your test script:
node hooks/examples/test.jsawait driver.get('https://www.lambdatest.com');
// Screenshot 1: Homepage
await driver.executeScript("smartui.takeScreenshot", {
screenshotName: 'homepage'
});
// Navigate and take another screenshot
await driver.get('https://www.lambdatest.com/pricing');
await driver.executeScript("smartui.takeScreenshot", {
screenshotName: 'pricing-page'
});let config = {
screenshotName: 'homepage-ignored',
ignore: ["antialiasing"],
ignoredBoxes: [
{ x: 0, y: 0, width: 100, height: 50 } // Ignore header area
]
};
await driver.executeScript("smartui.takeScreenshot", config);let config = {
screenshotName: 'homepage-bounded',
boundingBoxes: [
{ x: 100, y: 200, width: 800, height: 400 } // Compare only this area
]
};
await driver.executeScript("smartui.takeScreenshot", config);The smartUI.options in capabilities supports various configuration options:
- errorColor: RGB values for highlighting differences
- errorType: Type of error detection (
"movement","flat","flatDifferenceIntensity","movementDifferenceIntensity","diffOnly") - transparency: Opacity of the error overlay (0.0 to 1.0)
- largeImageThreshold: Threshold for large image comparison
- useCrossOrigin: Enable cross-origin resource sharing
- outputDiff: Generate difference images
- scaleToSameSize: Scale images to same size before comparison
- ignore: Ignore specific visual artifacts (
"antialiasing","colors","less","alpha","nothing")
After running your hooks-based tests, visit the LambdaTest Automation Dashboard to view:
- Test execution status
- Screenshots captured
- Visual comparison results
- Build and session details
Navigate to your SmartUI project in the SmartUI Dashboard to see detailed visual regression results.
- Connects to LambdaTest Cloud using Selenium Remote WebDriver
- Reads credentials from environment variables (
LT_USERNAME,LT_ACCESS_KEY) - Takes screenshot with name:
screenshot
- Runs Selenium locally using Chrome
- Requires Chrome browser installed
- Takes screenshot with name:
screenshot
Create the SmartUI configuration file using:
npx smartui config:create smartui-web.json- Use descriptive, unique names for each screenshot
- Include page/component name and state (e.g.,
homepage-logged-in,checkout-step-2) - Avoid special characters that might cause issues in URLs
- Use consistent naming conventions across your test suite
- Critical user flows: Login, checkout, payment
- Dynamic content: After user interactions, form submissions
- Responsive breakpoints: Different viewport sizes
- State changes: Before and after important actions
- Take screenshots only when necessary (not on every page load)
- Use
waitForPageRenderinsmartui-web.jsonfor slow-loading pages - Consider viewport-specific screenshots instead of full-page when possible
- Use ignore options to reduce false positives from dynamic content
try {
await driver.get('https://www.lambdatest.com');
await smartuiSnapshot(driver, "homepage");
} catch (error) {
console.error('Screenshot failed:', error);
// Handle error appropriately
throw error;
} finally {
await driver.quit();
}await driver.get('https://www.lambdatest.com');
await smartuiSnapshot(driver, "homepage");
await driver.findElement(By.linkText('Pricing')).click();
await smartuiSnapshot(driver, "pricing-page");
await driver.findElement(By.linkText('Documentation')).click();
await smartuiSnapshot(driver, "documentation-page");await driver.get('https://www.lambdatest.com');
// Wait for element and interact
const searchBox = await driver.findElement(By.id('search'));
await searchBox.sendKeys('Selenium');
await searchBox.sendKeys(Key.RETURN);
// Wait for results to load
await driver.wait(until.elementLocated(By.className('results')), 10000);
// Take screenshot after interaction
await smartuiSnapshot(driver, "search-results");const isLoggedIn = await driver.findElements(By.className('user-menu')).length > 0;
if (isLoggedIn) {
await smartuiSnapshot(driver, "homepage-logged-in");
} else {
await smartuiSnapshot(driver, "homepage-guest");
}name: SmartUI Visual Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
visual-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: |
cd sdk
npm ci
- name: Run SmartUI tests
env:
PROJECT_TOKEN: ${{ secrets.SMARTUI_PROJECT_TOKEN }}
LT_USERNAME: ${{ secrets.LT_USERNAME }}
LT_ACCESS_KEY: ${{ secrets.LT_ACCESS_KEY }}
run: |
cd sdk
npx smartui exec node sdkCloud.jspipeline {
agent any
environment {
PROJECT_TOKEN = credentials('smartui-project-token')
LT_USERNAME = credentials('lambdatest-username')
LT_ACCESS_KEY = credentials('lambdatest-access-key')
}
stages {
stage('Install Dependencies') {
steps {
sh 'cd sdk && npm ci'
}
}
stage('Run Visual Tests') {
steps {
sh 'cd sdk && npx smartui exec node sdkCloud.js'
}
}
}
}Solution: This is informational. The config file already exists. You can:
- Use the existing config file
- Delete it and create a new one:
rm smartui-web.json && npx smartui config:create smartui-web.json - Use a different config file:
npx smartui --config custom-config.json exec ...
Solution: Ensure the PROJECT_TOKEN environment variable is set:
export PROJECT_TOKEN='your_project_token'
# Verify it's set
echo $PROJECT_TOKENSolution:
- Verify your credentials are set correctly:
echo $LT_USERNAME echo $LT_ACCESS_KEY
- Check your credentials in LambdaTest Profile Settings
- Ensure there are no extra spaces or quotes in the environment variables
Solution: Install dependencies:
cd sdk
npm install @lambdatest/smartui-cli @lambdatest/selenium-driver selenium-webdriverSolution:
- Verify the
PROJECT_TOKENmatches your SmartUI project - Check that the build completed successfully (no errors in terminal)
- Wait a few moments for screenshots to process
- Verify you're looking at the correct project in the dashboard
Solution:
- Update ChromeDriver:
npm install --save-dev chromedriver - Or use WebDriver Manager:
npm install --save-dev webdriver-manager - Ensure Chrome browser is up to date
Solution:
- Increase
waitForPageRenderinsmartui-web.json:{ "web": { "waitForPageRender": 60000 } } - Add explicit waits before taking screenshots:
await driver.wait(until.elementLocated(By.id('main-content')), 10000); await smartuiSnapshot(driver, "screenshot");
Solution:
- Use ignore options for dynamic content (ads, timestamps, etc.)
- Increase
waitForTimeoutinsmartui-web.jsonfor lazy-loaded content - Use viewport-specific screenshots instead of full-page when appropriate
- Review and update baseline screenshots when intentional changes are made
{
"web": {
"browsers": ["chrome", "firefox"],
"viewports": [
[1920, 1080],
[1366, 768],
[360, 640]
],
"waitForPageRender": 30000,
"waitForTimeout": 2000
}
}Tips:
- Start with fewer browsers/viewports for faster initial testing
- Adjust
waitForPageRenderbased on your page load times - Use
waitForTimeoutfor async components (lazy-loaded images, animations)
Create different config files for different environments:
# Development
npx smartui --config smartui-dev.json exec node sdkLocal.js
# Staging
npx smartui --config smartui-staging.json exec node sdkCloud.js
# Production
npx smartui --config smartui-prod.json exec node sdkCloud.jsAfter running the tests, visit your SmartUI project dashboard to view the captured screenshots and compare them with baseline builds.
- Baseline Created: First run creates baseline screenshots
- Passed: Screenshot matches baseline (no visual differences)
- Failed: Visual differences detected
- Review Required: Manual review needed for differences
- Update baseline when intentional UI changes are made
- Review failed comparisons to identify false positives
- Use ignore options to exclude known dynamic content
- SmartUI Selenium JavaScript Onboarding Guide
- LambdaTest Selenium Documentation
- SmartUI Dashboard
- LambdaTest Automation Dashboard
- LambdaTest Community
- LambdaTest Blog
For additional help: