TestCafe Debugging and Troubleshooting: Fix Flaky Tests Fast

TestCafe Debugging and Troubleshooting: Fix Flaky Tests Fast

TestCafe failures divide roughly into three categories: selector timeouts, action failures, and assertion mismatches. Each has a distinct debugging approach. Spending 30 minutes understanding the right debugging workflow saves hours of adding await t.wait(2000) everywhere.

Debug Mode

The fastest way to understand a failure is to run it in debug mode:

testcafe chrome tests/checkout.test.js --debug-mode

Debug mode pauses execution before each action. You get a Resume button in the browser and a Next Step button to advance one action at a time. The browser stays open — you can inspect elements, check the console, and see exactly what state the page is in when the failure occurs.

Debugging from Code

Insert breakpoints programmatically:

test('Checkout flow', async t => {
  await t
    .click('#add-to-cart')
    .debug()  // Pauses here — browser stays open
    .click('#checkout');
});

t.debug() works mid-chain. Use it to isolate exactly which step is causing problems without modifying the runner command.

Skip Debug on Specific Steps

If you're debugging one part of a longer test and don't want to step through the setup:

test('Complex flow', async t => {
  // Setup — runs without pausing
  await t.useRole(adminRole);
  await t.navigateTo('/orders');
  
  // Problem area — pause here
  await t.debug();
  await t.click('.order-row:first-child');
});

Screenshots and Videos

On-Failure Screenshots

The most useful CI debugging feature:

testcafe chrome:headless --screenshots path=reports/screenshots,takeOnFails=true tests/

Or in config:

// .testcaferc.js
module.exports = {
  screenshots: {
    path: 'reports/screenshots',
    takeOnFails: true,
    fullPage: true,
  }
};

Screenshots show exactly what was on screen at the moment of failure. Combined with the error message, this usually pinpoints the problem without needing to reproduce locally.

Manual Screenshots

Take screenshots at specific points to trace state:

test('Upload flow', async t => {
  await t.click('#upload-btn');
  await t.takeScreenshot('after-upload-click');
  
  await t.expect(Selector('.upload-progress').exists).ok();
  await t.takeScreenshot('progress-visible');
});

Screenshots are saved to the configured path with the provided name.

Video Recording

testcafe chrome:headless --video reports/videos tests/

Video is recorded per test. On failure, you see the full interaction. This is slower than screenshots but invaluable for timing-related failures where you need to see the sequence of state changes.

Video options:

module.exports = {
  videoOptions: {
    singleFile: false,  // Separate file per test
    failedOnly: true,   // Only record failing tests (saves disk)
    pathPattern: '${DATE}_${TIME}/${FIXTURE}/${TEST_INDEX}/${USERAGENT}/${FILE_INDEX}.mp4'
  }
};

Client-Side Code Execution

When you need to inspect browser state that TestCafe's API doesn't expose directly:

const consoleErrors = await t.eval(() => {
  return window.__consoleErrors || [];
});
// Check localStorage
const authToken = await t.eval(() => localStorage.getItem('auth_token'));
await t.expect(authToken).ok('Auth token should be set after login');
// Run arbitrary DOM queries
const tableData = await t.eval(() => {
  const rows = document.querySelectorAll('#data-table tbody tr');
  return Array.from(rows).map(row => row.cells[0].textContent);
});
console.log('Table data:', tableData);

t.eval() runs synchronously in the browser context. For async operations:

const apiResponse = await t.eval(async () => {
  const res = await fetch('/api/status');
  return res.json();
});

Client-Side Console Logging

Capturing browser console output in test logs:

fixture('My Feature')
  .clientScripts({
    content: `
      const originalError = console.error;
      console.error = (...args) => {
        window.__consoleErrors = window.__consoleErrors || [];
        window.__consoleErrors.push(args.join(' '));
        originalError(...args);
      };
    `
  });

This captures client-side errors so you can assert on them or log them from test code.

Request Hooks for API Debugging

TestCafe's request hooks let you inspect and mock network calls:

import { RequestLogger, RequestMock } from 'testcafe';

// Log all API requests
const apiLogger = RequestLogger('https://api.example.com', {
  logRequestBody: true,
  logResponseBody: true,
  logResponseHeaders: true,
});

fixture('API calls')
  .requestHooks(apiLogger);

test('Form submits correct data', async t => {
  await t.click('#submit-form');
  
  // Check what was sent
  await t.expect(apiLogger.count(() => true)).eql(1);
  const request = apiLogger.requests[0];
  
  console.log('Request body:', request.request.body);
  await t.expect(JSON.parse(request.request.body).email).eql('user@example.com');
});

For mocking:

const mock = RequestMock()
  .onRequestTo('https://api.example.com/users')
  .respond({ users: [] }, 200, { 'Content-Type': 'application/json' });

fixture('Empty state')
  .requestHooks(mock);

Common Failure Patterns

Selector Timeout

Error: The specified selector does not match any element in the DOM Tree.
      > | Selector('#submit-btn')

Causes:

  1. Element doesn't exist at all — wrong selector or page not loaded
  2. Element exists but is not yet rendered — async content still loading
  3. Element is inside an iframe — TestCafe needs switchToIframe() first

Debug:

// Check if element exists first
const exists = await Selector('#submit-btn').exists;
console.log('Button exists:', exists);

// Check element count
const count = await Selector('button').count;
console.log('All buttons:', count);

// Get all button text to find the right one
const buttons = await t.eval(() => 
  Array.from(document.querySelectorAll('button')).map(b => b.textContent)
);
console.log('Buttons:', buttons);

Element Not Visible

Error: The element is not visible.

Causes:

  1. display: none or visibility: hidden
  2. Off-screen position
  3. Covered by another element (modal, overlay)

Debug:

const el = Selector('#target');
console.log('visible:', await el.visible);
console.log('offsetWidth:', await el.offsetWidth);
console.log('offsetHeight:', await el.offsetHeight);
console.log('boundingClientRect:', await el.boundingClientRect);

Action on Wrong Element

Tests click the right selector but the wrong element — often happens with lists where ordering changes.

Debug:

const target = Selector('.item').withText('Delete');
console.log('Element count:', await target.count);
console.log('Parent text:', await target.parent().textContent);

Role Initialization Failure

Error: Role initialization failed: The login button was not found.

This typically means your app's login page changed or the login flow has a new step.

Debug:

  1. Run the role URL directly in a browser
  2. Check if the login form selectors in your Role() definition still match
  3. Add screenshots to role initialization:
const adminRole = Role('https://app.example.com/login', async t => {
  await t.takeScreenshot('before-login');
  await t.typeText('#email', 'admin@example.com');
  await t.typeText('#password', 'secret');
  await t.click('#login-btn');
  await t.takeScreenshot('after-login-click');
  await t.expect(Selector('.dashboard').exists).ok({ timeout: 10000 });
});

Assertion Value Mismatch

AssertionError: expected '  Dashboard  ' to equal 'Dashboard'

Classic whitespace issue. TestCafe returns raw textContent which includes surrounding whitespace.

// Fragile
await t.expect(el.innerText).eql('Dashboard');

// Robust
await t.expect(el.innerText.trim()).eql('Dashboard');

// Or use contains
await t.expect(el.innerText).contains('Dashboard');

Slow Test Debugging

Use the --speed flag to slow down test execution — useful for spotting timing issues:

testcafe chrome tests/flaky.test.js --speed 0.5

Speed is 0.01 to 1 (1 = fastest). At 0.5, each action takes twice as long. If a flaky test passes at low speed, you have a timing issue, not a logic bug.

For targeted slow-down:

test.timeouts({ pageLoadTimeout: 30000 })('Slow page test', async t => {
  // ...
});

Logging and Reporting

Add structured logging that survives parallel runs:

import { t } from 'testcafe';

async function log(t, message) {
  const timestamp = new Date().toISOString();
  console.log(`[${timestamp}] ${message}`);
}

test('Checkout', async t => {
  await log(t, 'Starting checkout test');
  await t.click('#cart');
  await log(t, 'Cart opened');
  // ...
});

For CI integration, use the JUnit reporter:

testcafe chrome:headless --reporter junit:reports/results.xml tests/

Continuous Failure Monitoring

Once your tests are stable locally, flakiness in CI is often caused by environmental differences: slower machines, network latency, or backend inconsistencies.

HelpMeTest runs your tests on a schedule and tracks failure rates per test over time. Instead of investigating a CI run from 3 hours ago, you get a history of which tests are consistently failing vs. intermittently flaky — letting you prioritize fixes on tests with real problems rather than chasing noise.

Summary

TestCafe's debugging toolkit — debug mode, screenshots-on-failure, video recording, client-side eval, and request hooks — covers the full range of E2E test failures. For selector timeouts, check existence and visibility properties. For assertion failures, check whitespace and use contains instead of eql when appropriate. For timing issues, use --speed to confirm the root cause before adding timeouts. Fix the root cause; don't mask it with t.wait().

Read more

Start now free