Fixing Cypress Function Errors: Troubleshooting Guide

Abstract: Resolve the Cypress "function is not a function" error by fixing incorrect command chaining, missing return statements in custom commands, and improper asynchronous handling.

Created: 2026-08-17 by

Resolve the "function is not a function" error in Cypress by ensuring you are correctly chaining commands within your test suite. This issue typically arises when a command returns undefined or when asynchronous operations are mishandled, causing subsequent method calls to fail on non-function values.

Understanding the Error Context

The "function is not a function" error is a classic JavaScript runtime exception that manifests frequently in Cypress automation scripts. Unlike standard Node.js applications where errors might be caught gracefully, Cypress fails fast during test execution, halting the entire spec file immediately. This behavior is designed to prevent false positives, but it can be confusing for developers who expect the test to continue despite a minor assertion failure.

Cypress commands are asynchronous and return a special object called a Chainable. When you invoke a command like cypress.get() or cypress.click(), you are not getting the DOM element directly; you are getting a wrapper that holds the result. If you attempt to call a method on this wrapper incorrectly, or if the previous command in the chain resolves to something unexpected, the JavaScript engine throws this error because it expects a callable function but receives an object or primitive value instead.

Common Causes and Diagnostic Steps

Identifying the root cause requires examining the specific line of code where the error occurs. The most frequent culprits involve improper use of jQuery-like methods versus Cypress-specific commands, or incorrect handling of promises.

  • Incorrect Command Chaining: A common mistake is mixing native JavaScript array methods with Cypress commands. For example, calling .map() on a Cypress chain without understanding that it returns a new Chainable rather than a standard array can lead to type mismatches later in the pipeline.
  • Missing Return Statements: In custom commands defined in cypress/support/commands.js, failing to explicitly return the result of a Cypress command breaks the chain. Without the return statement, the next command in the sequence receives undefined, leading to the error when it tries to invoke a method on it.
  • Asynchronous Timing Issues: Attempting to access properties of an element before it has been fully rendered or available in the DOM can result in retrieving null or undefined. If a subsequent step assumes this property exists and is a function, the test will crash.

To diagnose these issues, enable verbose logging by running your tests with the --debug flag. This provides a detailed output of each command execution and its resolved value, allowing you to pinpoint exactly which variable holds the unexpected type.

Fixing Incorrect Command Usage

One of the primary solutions involves correcting how you interact with DOM elements. Ensure that you are using Cypress's built-in commands such as cy.get(), cy.contains(), and cy.find() exclusively for DOM traversal. Avoid using native jQuery methods like $().find() inside Cypress tests unless absolutely necessary, as they do not integrate with Cypress's automatic retry-ability and waiting mechanisms.

// Incorrect: Mixing jQuery with Cypress chains
cy.get('.button').then(($btn) => {
  $btn.find('span').click(); // This may break the chain context
});

// Correct: Using Cypress commands throughout
cy.get('.button')
  .find('span')
  .click();

In the correct example above, cy.get() returns a Chainable, and .find() is a valid method on that Chainable. This maintains the integrity of the promise chain and ensures that each step waits for the previous one to complete successfully.

Properly Handling Custom Commands

If you have created custom commands in your support file, verify that every command returns the appropriate Cypress object. A typical custom command should look like this:

Cypress.Commands.add('login', (username, password) => {
  cy.visit('/login');
  cy.get('#username').type(username);
  cy.get('#password').type(password);
  cy.get('form').submit();
  // Crucial: Return the result to maintain chainability
  return cy.url(); 
});

By returning cy.url(), the caller can chain further assertions like .should('include', '/dashboard'). Omitting the return statement causes the caller to receive undefined, triggering the error when it attempts to call .should().

Managing Asynchronous Operations

When dealing with external APIs or complex asynchronous logic, avoid using async/await directly inside Cypress test cases unless you are careful about how results are passed back into the Cypress chain. Instead, use cy.then() to handle raw JavaScript logic within the Cypress queue.

cy.request('GET', '/api/data')
  .then((response) => {
    const data = response.body;
    // Process data here
    return data.items;
  })
  .then((items) => {
    items.forEach(item => {
      cy.log(item.name);
    });
  });

This approach keeps all operations within the Cypress event loop, ensuring that retries and timeouts are managed correctly by the framework.

Frequently Asked Questions

Why does my test pass locally but fail in CI?

Differences in browser versions, network speeds, or system resources between local and CI environments can affect timing. Ensure your tests include explicit waits or rely on Cypress's default retry-ability rather than hardcoded delays like cy.wait(5000).

How do I debug a specific line throwing this error?

Use the Cypress Test Runner's interactive mode and add cy.pause() before the failing line. This allows you to inspect the current state of the application and manually execute commands in the console to see what values are being returned.

Can I ignore this error and continue the test?

No, this is a fatal JavaScript error that stops script execution. You must fix the underlying code logic. Ignoring it is not possible without wrapping the code in a try-catch block, which is generally discouraged in Cypress as it masks failures.

Is this error related to network connectivity issues?

While network issues can cause requests to fail, they typically result in different error messages like "request failed" or "timeout." The "function is not a function" error is strictly a code logic issue regarding object types and method availability.

What is the difference between cy.then() and .then()?

cy.then() is a Cypress command that yields the previous subject and executes a callback within the Cypress queue. Native .then() is a Promise method that runs outside the Cypress queue, which can lead to race conditions and loss of automatic retries.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More