Identifying JavaScript Errors in a Web Page: A Guide to Cypress

Currently, I am working on creating a spec file that contains N it(s), with each it visiting a specific page within the application and returning the number of errors/warnings present.

I have also shared my query here: https://github.com/cypress-io/cypress/issues/4808

Unfortunately, the suggested solution does not appear to be effective:

it('should spy window.error', () => {
  cy.visit('https://www.spiegel.de/', {
    onBeforeLoad(win) {
      cy.spy(win.console, 'error').as('spyWinConsoleError');
      cy.spy(win.console, 'warn').as('spyWinConsoleWarn');
    },
  })
  console.error('questo e errore')
  cy.get('@spyWinConsoleError').should('be.calledOnce');
});

Any thoughts or suggestions on how to resolve this issue?

Answer №1

There are a couple of key points worth noting:

  • It's important to understand that in a Cypress test, there are two window objects - the one the test operates in and the one the application operates in. When you use console.error('questo e errore'), you are referring to the first window, while your spy is set on the second window.

  • Another crucial point is that test code executes faster than Cypress commands. This means that console.error('questo e errore') may run before cy.visit() completes.

Below are some examples that demonstrate these concepts:

Spying on runner window console

it('should spy on RUNNER window.error', () => {
  cy.spy(window.console, 'error').as('spyWinConsoleError');
  console.error('questo e errore')
  cy.get('@spyWinConsoleError').should('be.calledOnce');
});

Spying on app window console

it('should spy on APP window.error', () => {
  const win = cy.state('window')
  cy.spy(win.console, 'error').as('spyWinConsoleError');
  
  win.console.error('questo e errore')
  cy.get('@spyWinConsoleError').should('be.calledOnce');
});

Catching an actual app error

it('should spy window.error', () => {
  cy.visit('../app/spy-on-win-error.html', {
    onBeforeLoad(win) {
      cy.spy(win.console, 'error').as('spyWinConsoleError');
    },
  })
  cy.get('@spyWinConsoleError').should('be.calledWith', 'from app');
});
<body>
  <script>
    setTimeout(() => {
      console.error('from app')
    }, 1000)
  </script>
</body>

Waiting for spiegel.de to load

it('should spy window.error', () => {

  cy.visit('https://www.spiegel.de/', {
    onBeforeLoad(win) {
      cy.spy(win.console, 'error').as('spyWinConsoleError');
      win.console.error("questo è l'errore due");      // call here after spy is set
    },
  })

  cy.get('@spyWinConsoleError')
    .should('be.calledOnce');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the solution for fixing the "Invalid Element Type" error?

Hey there! I'm currently working on creating a Twitter clone using React, but I've run into an error that's giving me some trouble. The error message reads: "Element type is invalid: expected a string (for built-in components) or a class/fu ...

Show the error message from passport.js authentication in the user interface

I am currently working on a new project with Sails.js and using Passport.js for user authentication. Despite having the basic authentication set up, I am struggling to display error messages in the login view when incorrect credentials are entered. I have ...

Exploring the Potential of Mobile Development using AngularJS

I am in the process of creating an app with the following key design objectives: Efficiency and modularity - a light core that can be expanded to create a feature-rich app in a cohesive manner Mobile focus - this app is primarily aimed at mobile platform ...

Trouble displaying image due to issues with javascript, html, Angular, and the IMDb API integration

I have been working on displaying images from the IMDb API in my project. Everything works perfectly fine when I test it locally, but once I deploy the project to a server, the images do not load initially. Strangely, if I open the same image in a new tab ...

What is the best way to display a loading animation until the entire wizard has finished loading in the jQuery-steps

I need help with implementing a loading animation using the jQuery-steps plugin in my wizard type form. I want the animation to be displayed until the entire wizard has loaded completely, but I'm unsure of how to enable this feature as there is a labe ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Utilizing getServerSideProps and getInitialProps in Next.js to optimize page loading times

My page is not loading when I use getServerSideProps or getInitialProps. It keeps on loading without displaying the content, but everything works fine when I remove them. What could be wrong with my code here? HELP. ... interface Props { data: any; } co ...

Some places may not have detailed information available when using the Google Places API

Greetings I am currently in the process of developing a page on my website that utilizes the Google Places API along with the user's geographical coordinates (latitude, longitude) to locate nearby restaurants. In my code, I have implemented a functio ...

Steps to create a conditional AJAX request triggered by the onbeforeload event depending on the value of a variable

My website script tracks user login status in real time using "onbeforeunload", ajax, and logout.php. This method updates the MySQL database with a value of 1 or 0 to indicate if a user is logged in. Unlike monitoring cookies, this approach allows accurate ...

Ways to showcase the contents of a React JavaScript document, or more specifically, a file designed for React interpretation

After trying multiple solutions, I found a conceptual guide on How to call and form a React.js function from HTML. However, the HTML generated doesn't seem to be calling from the JavaScript file as expected. It appears identical to what is mentioned i ...

In jqGrid's gridComplete event, we can use the getRowData method to retrieve the value of a

Seeking guidance on extracting variables from jqGrid getRowData method While iterating through rows, I simply want to retrieve the ID and Phrase column values into separate variables gridComplete: function () { var allRowsInGrid = $('#list'). ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

Having trouble obtaining the ref.current.offsetWidth?

I have been working on creating a contextMenu. My goal is to retrieve the offsetWidth and offsetHeight from ref.current, but when I console.log it, it shows as undefined. const ContextMenu: React.FC<ContextMenuProps> = props => { const thisCom ...

Having trouble initialising an array of objects in TypeScript? (TS1109: Expression expected)

While working on my project, I encountered a problem when trying to create an array of objects: Error TS1110: Type expected Error TS1109: Expression expected https://i.sstatic.net/Y5qb8.png This is how my array is structured: export let COUNTRIES: A ...

Modifying webpack settings for a create-react-app based project: A step-by-step guide

After starting a new react project with create-react-app, I am looking to update the webpack configuration. However, I cannot seem to locate the webpack file. Should I be creating this file myself, or is there another process involved? As someone who is ...

Adjusting the background color of a MuiList within a React Material-UI Select component

Looking to customize the background color of the MuiList in a react material-ui Select component without affecting other elements. Specifically targeting the Select element with the name 'first'. Despite setting className and trying different cl ...

Implementing dynamic active class changes in a navbar with JavaScript

My goal was to have the navbar change its class to 'active' dynamically when a user clicks on the <li> tag. Can you help me pinpoint where I made a mistake? dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a'). ...

Slideshow Display Suddenly Halts at the Last Image

I am currently working on a Bootstrap JS Carousel that showcases several images stored in the project folder. Each image's filepath is retrieved from an SQL Server database and displayed within the carousel. While the images are displaying correctly ...

What is the method to determine the number of keys that have the same value in a JavaScript object?

My goal is to achieve functionality similar to this: var data = [ { tag:'A', others:'Abc' }, { tag:'B', others:'Bbc' }, { tag:'A', others ...

Comparison: Chrome extension - utilizing default pop-up vs injecting a div directly into the page

I find myself perplexed by the common practices used in popular Chrome extensions. I am currently working on creating my own Chrome extension and after completing a basic tutorial, I have set up a default popup page that appears when clicking the extensi ...