• 27-Dec-2022
Lightrun Team
Author Lightrun Team
Share
This is a glossary of all the common issues in Cypress-io Cypress

Troubleshooting Common Issues in Cypress-io Cypress

Lightrun Team
Lightrun Team
27-Dec-2022

Project Description

Cypress is a JavaScript-based test automation framework that is designed to make it easy to write, run, and debug automated tests for web applications. It is focused on providing a good developer experience, with features such as automatic waiting for elements to appear on the page, time travel debugging, and a command log that allows you to see exactly what happened during a test.

Cypress can be used to test applications built with any web technology, including HTML, CSS, and JavaScript. It can run tests in a real browser, simulating the behavior of a user interacting with the application, and it can also run tests in a headless browser, which allows for faster test execution.

Cypress is built on top of the Mocha test runner and the Chai assertion library, and it uses the BDD (behavior-driven development) style of testing, which emphasizes specifying the expected behavior of the application under test.

Troubleshooting Cypress-io Cypress with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

The following issues are the most popular issues regarding this project:

DOMexception: Document is not focused

Testing the copy button’s ability to correctly duplicate a selected value from our select component appears unreliable, with failure occurring in around 50% of attempts. This issue can be conveniently replicated by running Cypress interactively and focusing on its development tools window during execution.
Our application test window is losing focus on the browser’s development tools in certain scenarios, making it difficult for us to identify why. Even more puzzlingly, this behavior occurs non-deterministically even when dev tools are inactive or not visible – an occurrence that we have yet been unable to explain.
After much experimentation, a viable solution was found to the challenge of ensuring that text could be copied within an allotted timeframe. Utilizing common sense proved unsuccessful in achieving this outcome; however, confirmation with cypress’ ‘cy.focused’ function indicated that centering focus on the test window enabled successful copying results afterward.

For maximum accuracy, ensure that your cursor’s attention is on the copy icon/button before tapping it. To achieve this, use cy.realClick from cypress-real-events instead of a regular click command.

Combining cy.focus and cy.click appears to provide an effective workaround for the issue at hand, although this should not be viewed as a long-term solution. Despite more than twelve tests confirming its efficacy, there is always potential that luck played a part in obscuring whatever caused the problem in the first place – making it all the more crucial that Cypress use their expertise to properly root out what exactly has gone wrong here.

Provide a “Cypress” way to access textContent (and/or innerText) – .text() command

Leverage jQuery’s powerful methods to access text content within HTML elements. Unlock the full potential of your web development projects with these dynamic tools!

cy.get('element').invoke('text')

Capture + Display all logs for everything that happens in Cypress

To effectively utilize the available functions, we suggest utilizing plugins to ensure that our workflow remains efficient and productive.

https://github.com/flotwig/cypress-log-to-output – Cypress now delivers automated browser logging to the terminal, providing enhanced visibility of your tests in real-time. To take advantage of this feature, simply run any Cypress tests on Chrome.

https://github.com/bahmutov/cypress-failed-log – Cypress tests can be saved as an easily cataloged JSON file should any failures occur, allowing for concise post-analysis.

https://github.com/archfz/cypress-terminal-report – Automatically detect and analyze cypress commands, route requests, and browser console errors when tests fail on the CI environment to provide an efficient debugging experience.

Login through Azure AD account.

If you’re seeking to verify Single Sign-On (SSO) capability, Cypress provides step-by-step instructions on how to do this. It is recommended that third-party sites not under your control should not be visited or tested directly; instead, programmatic testing via cy.request can more quickly and reliably confirm the integration between it and your application with complete confidence. To apply these principles in practice, take a look at their provided recipe for further guidance!

https://docs.cypress.io/guides/references/best-practices.html#Visiting-external-siteshttps://docs.cypress.io/examples/examples/recipes.html#Single-Sign-On

can’t trigger ‘onChange’ for an input type=’range’ rendered by React

We have devised an innovative solution to this problem that does not involve the need for switching input events. Our approach has been carefully crafted so as to be both effective and efficient!

Implementing the proper value to a DOM node without inadvertently overruling React’s parameters is achievable.
Triggering a change event causes React to pick up and respond to any alterations.

Re-query elements that are found ‘detached’ from the DOM

Cypress v12.0.0 triumphantly resolves this issue, allowing for a graceful and effortless solution to the problem at hand!

Cypress Custom Command typings need better documentation

Fix is bringing Cypress into the global spotlight, as well as any custom command definitions associated with it.

declare global {
  namespace Cypress {
    interface Chainable {
      customCommand: typeof customCommand;
    }
  }
}

function customCommand(input: MyCustomClass) {
  // ...
}

Cypress.Commands.add('customCommand', customCommand);

Default headers for cy.request command

To address a technical issue, one potential solution is to replace the existing cy.request command with an alternative custom version.

Cypress.Commands.overwrite('request', (originalFn, ...options) => {
  const optionsObject = options[0];

  if (optionsObject === Object(optionsObject)) {
    optionsObject.headers = {
      authorization: 'Bearer YOUR_TOKEN',
      ...optionsObject.headers,
    };

    return originalFn(optionsObject);
  }

  return originalFn(...options);
});

should(‘have.text’, …) should ignore leading and trailing whitespace

An effective approach may be to consider the following:

cy.get('...').should($el => expect($el.text().trim()).to.equal('...'));

An alternative solution is available for use:

cy.get('.message').should('contain.text', message)

Ability to prevent/stop loading ‘Page load’

To find a solution to an obstacle, one might consider approaching the problem with innovative thinking and alternative strategies. This can often lead to inventive workarounds that may not have been considered before.

cy.window().document().then(function (doc) {
  doc.addEventListener('click', () => {
    setTimeout(function () { doc.location.reload() }, 5000)
  })
  cy.get('[ng-click="vm.export()"]').click()
})

Move the cursor (Drag and Drop)

After delving into the drag-and-drop feature, it was observed that elements were not dropping to their intended destinations. Consequently, all three position properties had to be set manually in order for them to reach the desired spot.

 cy.get( selector )
    .trigger('mousedown', { button: 0 })
     .wait(1500)
     .trigger('mousemove', {
    clientX: 80,
      clientY: 90,
     screenX: 80,
    screenY: 90,
   pageX: 80,
     pageY: 90
     })
   .trigger('mouseup', { force: true });

While attempting to implement a single property proved unsuccessful, the successful implementation of all three has proven more effective.

Ability to console.log output from test files to stdout when running via `cypress run`

I switched up my approach and successfully implemented a task command, replacing the log one in commands/index.

Cypress.Commands.overwrite('log', (subject, message) => cy.task('log', message));

To improve user experience, a task command has been integrated into the plugins module located inplugins/index.

module.exports = on => {
  on('task', {
    log (message) {
      console.log(message);
      return null
    }
  });
};

All cy.log() messages will be printed to the console for easy retrieval and review.

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module error thrown

For me, success was achieved through the renaming of the plugin’s index to ‘index.cjs’ and its subsequent definition in the cypress.json configuration file.

{
  ...
  "pluginsFile": "cypress/plugins/index.cjs",
  ...
}

Angular-CLI with Jasmine unit tests, Chai types conflict

Facing a similar predicament, it appears this is merely a Visual Studio Code issue. Nevertheless, the execution of unit tests and end-to-end operations remain unaffected. Fortunately for us all, solutions to these kinds of predicaments can be found by referencing https://github.com/cypress-io/cypress/issues/1087#issuecomment-552951441.

To ensure the proper functioning of the application, it is important to modify the primary tsconfig.json file as opposed to any other configuration files such as tsconfig.app.json or tsconfig.spec.json

{
    "include": [
        "src",
        "node_modules/cypress"
    ],
    "exclude": [
        "node_modules/cypress"
    ]
}

VS code appears to be prioritizing one configuration file over another, while only allowing previously included files the opportunity of being excluded.

cy.request(…) fails if server is not available, with no option to return or catch the connection error

To make cy.request even more powerful, a new option can be added to give users greater control over their HTTP requests.

cy.request({
	url: 'http://something.invalid',
    failOnNetworkError: false // default: true
})
.then(res => {
	// res is an object with the Node.js Error `code` and `message` attached
    // should probably either have `res.error = true` or `res.error = { code, message }`
    // so users can tell it apart from a success
})

Conditional testing of DOM elements

For the most intricate of scenarios where multiple platforms are involved, conditional tests can prove to be a revelation. As demonstrated in the example given for statement checking, this approach may very well deliver satisfactory results – something that would otherwise remain elusive.

Cypress.$('body').find(elementLocator).length > 0

In order to mitigate the inevitable delays associated with condition waiting, we should explore viable solutions.

let i = 0
for(i, i < 10, i ++){
    if(Cypress.$('body').find(elementLocator).length > 0){
        break;
    }

    cy.wait(1000)
}

Although this may not be a comprehensive solution, it can certainly serve as the foundation for something more effective. By combining it with recursion, our approach to problem-solving becomes much more flexible and reliable – ready to tackle any challenge that comes its way.

try{
    cy.get(elementLocator)
}catch(e){
    // do something
}

EEXIST: file already exists – cannot start server on Windows

Include the following script within your package.json file for an enhanced user experience!

{
  "scripts": {
    "test": "cypress open"
  }
}

Execute the command to be informed of applicable results!

npm run test

Headless operations can often prove difficult and are a common source of difficulty in many areas.

Headless operations can often prove difficult and are a common source of difficulty in many areas.

By implementing a continuous integration and delivery pipeline optimized to run in full mode, we can ensure smooth running of our system. This approach allows us to deploy changes with minimal disruption while also providing rapid feedback so any issues can be addressed quickly.

xvfb-run cypress run --headed --browser chrome --spec 'cypress/integration/non-prod/**'

cypress run times out waiting for the browser to connect

Utilizing their own initiative, the issue was successfully solved by going ‘headed’.

xvfb-run cypress run --headed --browser chrome --spec 'cypress/integration/non-prod/**'

Mock websockets

Cypress provides a workaround for mocking WebSockets – utilizing onBeforeLoad in visit and the mock-socket library to create an efficient simulation of the actual function.

onBeforeLoad(win) {
    // Call some code to initialize the fake server part using MockSocket
    cy.stub(win, "WebSocket", url => new MockSocket.WebSocket(url))
}

Run selected subset of files from Cypress interface (multiple tests)

With 4.12.0, users are now able to choose specific files based on pre-defined search criteria and have them processed automatically!

Get the full information you need to complete your task with these easy-to-follow instructions. Ensure success and confidence in a job well done!

https://on.cypress.io/writing-and-organizing-tests#Run-filtered-specs

Instruction, how to run multiple tests in Cypress

cy.get().contains() does not accept new DOM elements

cy.contains(‘.myDiv’,’Expectation’) operates smoothly and yields successful results as anticipated.

Error: read ECONNRESET with fresh npm install

After diligent investigation, we identified Sophos’ Network Threat Protection as the cause of our issue. With this disabled, operations returned to normal and harmony was restored!

Thing, that should be turned off(Network Threat Protection)

Cannot read properties of null (reading ‘append’) – @cypress/vue

After careful examination and assessment of the auto-generated component-index..html, we made a successful modification to line 10 from <div data-cy-root> to<div data-cy_root id=”__cy_root”></div>, thereby resolving the issue.

Hide XHR requests from the command log

Cypress’ logging internals was explored in depth, leading to the discovery of an innovative solution: hiding fetch and XHR command log entries with CSS.

https://gist.github.com/simenbrekken/3d2248f9e50c1143bf9dbe02e67f5399

More issues from Cypress-io repos

Troubleshooting github-action

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications. It’s a registration form away.

Get Lightrun

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.