19

What is the difference between a Custom Command and a Task? I am trying to understand how they should each be used.

Custom Command documentation: https://docs.cypress.io/api/cypress-api/custom-commands.html

Task documentation: https://docs.cypress.io/api/commands/task.html

2
  • 3
    Someone from the Cypress gitter.im answered with this, I found it helpful: "You cannot run any type of node related operation within Cypress context. As all your code is bundled and sent to Cypress instance. Node commands for example console.log() will not run in your tests or page objects. Suppose you want to clean mongo database tables, so you will use the Cypress tasks inside index.js in plugins. Coming to commands, It’s as simple as creating custom methods you want to create, you can do it in Commands.js file."
    – remjx
    Commented Nov 3, 2019 at 13:58
  • 1
    One rule of thumb could be: could this code go into a before or beforeEach callback? If yes, then it's a Custom Command. For instance, tasks cannot call existing cy commands (say setting a cookie with cy.setCookie), while custom commands can.
    – Eric Burel
    Commented Apr 15, 2020 at 8:08

3 Answers 3

47

A command (most methods on the global cy object) is a function that enqueues (pushes) an action to a queue of currently-executing commands. The queue executes serially and asynchronously (that's why return value of a command is an object having a .then method --- but despite that and the fact it behaves like promise, it's not a promise). Until a previous command is finished, the next command doesn't execute.

Commands are defined and executed directly in the browser.

A custom command is a regular command, but defined by you as opposed to the default commands that Cypress supplies out of the box. Custom commands are useful for automating a workflow you repeat in your tests over and over (e.g. by grouping several default cy commands together).

Commands are used to interact with your web app under test (AUT) --- most notably with the DOM (e.g. via cy.get(selector) to query the DOM), and to make assertions.

It's also important to realize that while commands are being executed serially, they are enqueued immediately (in the same event loop tick), and any expressions you pass to them are evaluated then and there. This isn't a Cypress-specific behavior, just plain JavaScript. That's why you can't do things like these:

// INCORRECT USAGE
let value;
cy.get('.myInput').invoke('val').then(val => value = val);
cy.get('.mySecondInput').type(value); // ✗ value is undefined here

Nor can you use async/await:

// INCORRECT USAGE
let value;
// ✗ doesn't work on Cypress commands
const value = await cy.get('.myInput').invoke('val');
cy.get('.mySecondInput').type(value); 

A task is a function defined and executed on the Cypress backend process (Node.js), not in the browser.

To execute a task (which you previously defined in your cypress/plugins/index.js file), you need to first enqueue it as a regular command in your test via cy.task(taskName, data). Cypress then (when the command takes its turn to execute) sends a message to the backend process where the task is executed.

Data your task returns is serialized (via JSON.stringify or something similar) and sent back to the browser where it's passed to a callback you potentially chained to your cy.task() command using .then(callback).

Tasks are mainly used to communicate with your own server backend, to e.g. seed the database; or for I/O such as reading/writing to a file (although cypress supplies commands for these such as cy.exec() or cy.writeFile()).

There are no default tasks --- every task you execute you first need to define yourself.

Another important point is that the messages that are sent between processes (the Cypress browser process, and the Cypress node process) are sent via an IPC channel, and must be serializable. That means that the data you pass to cy.task(taskName, data) are stringified, as well as is the response returned from the task itself. Thus, sending e.g. an object containing a method will not work (that is, the method won't be transferred at all).

4
  • 8
    Great explanation that seems completely absent from the otherwise comprehensive cypress docs.
    – gap
    Commented Apr 24, 2020 at 1:00
  • 1
    Awesome explanation. I went over the cypress docs after reading your explanation and found that to be super understandable now. In my case, commands function has been under used but I guess right now, i could use the commands to basically group a set of similar commands that is used to perform a function on a feature instead of redundantly writing the execution steps in each test file
    – Emjey
    Commented Sep 23, 2020 at 11:43
  • 1
    @Emjey From docs.cypress.io/api/cypress-api/… Custom commands work well when you’re needing to describe behavior that’s desirable across all of your tests. it’s often more efficient to write a JavaScript/typescript function for repeatable behavior Commented Oct 23, 2020 at 7:16
  • 2
    Note that it's also possible to use cy.exec() to run arbitrary commands like e.g. seeding a database. This can be used in commands as well. For simple one-off commands, It can sometimes be simpler than defining a task.
    – kschiffer
    Commented Jan 13, 2021 at 12:25
3

Great answers but in order to sum up, here are two main differences that help you choose whether you need a Cypress command or a task :

  • If you need to run a promise or interact with your backend, go with a task.
  • If you are interacting with the DOM and making assertions, go with a command.

Taken from this article

1
  • Very usefule points. Commented Aug 24, 2023 at 23:52
0

Cypress commands, in general do not return promises. The documentation refers to them as 'thenable', it simply means the results are only obtained via the .then(result=>{}) construct.

This is why the comment above is true. (Shown here for reference)

    // INCORRECT USAGE
    let value;
    // ✗ doesn't work on Cypress commands
    const value = await cy.get('.myInput').invoke('val');
    cy.get('.mySecondInput').type(value); 

However, there is a native way to wrap cypress command to get true async/await behavior as shown here:

    function getAsync(query, cb) {
      let prom = new Promise<any[]>((resolve, reject) => {
        cy.get(query).then((elements) => {
          let objArray = [];
          if (elements === undefined) {
            reject();
          }
          elements.each((index) => {
            let element = elements[index];
            let obj = cb(element);
            objArray.push(obj);
          });
          resolve(objArray);
        });
      });
      return prom;
    }

To call this function above:

  it('Gets specific DOM Elements', async () => {
    let data = await getAsync('form', getForm); 
  ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.