Cypress - RangeError: The Date.toISOString method is throwing an error due to an invalid time

Running cypress version 13.9.0, I encountered a RangeError while using cy.reload(). The error points to an Invalid time value at Date.toISOString.

Any suggestions on how to resolve this issue?

  waitForUpdate(employeeId, employeeName, employeeEmail) {
    const token = JSON.parse(localStorage.getItem('activeToken')).token.token;
    
    // Start a clock to control the timeout
    cy.clock(new Date()); 

    const checkStatus = () => {
      cy.request({
        method: 'GET',
        url: Cypress.config().baseUrl + `api/v1/employee/${employeeId}`,
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }).then((response) => {
        expect(response.status).to.equal(200);
        const { name, email } = response.body;

        if (name === employeeName && email === employeeEmail) {
          // Task found and status is as expected
          cy.log("Employees' data updated");
          cy.reload();
        } else if (new Date().getTime() - startTime < 900000) {
          // Retry for a maximum of 15 minutes (900000 milliseconds)
          // eslint-disable-next-line cypress/no-unnecessary-waiting
          cy.wait(15000); // Wait for 15 seconds
          checkStatus(); // Retry the request
        } else {
          // Timeout exceeded, fail the test
          cy.log('Employees data is not updated within 15 minutes.');
          expect(false).to.equal(true); // Fail the test
        }
      });
    };

    const startTime = new Date().getTime();
    checkStatus(); // Start checking the status
  }

Above code throws the following error:

RangeError: The following error originated from your application code, not from Cypress.

  > Invalid time value

When Cypress detects uncaught errors originating from your application it will automatically fail the current test.

This behavior is configurable, and you can choose to turn this off by listening to the `uncaught:exception` event.
    at Date.toISOString (<anonymous>)
    at q.end (main.a1444de99b433347.js:1:216062)
    at HTMLDocument.<anonymous> (main.a1444de99b433347.js:1:62383)
    at I.invokeTask (polyfills.2ba72d64643256ee.js:1:7246)
    at B.runTask (polyfills.2ba72d64643256ee.js:1:2614)
    at b.invokeTask [as invoke] (polyfills.2ba72d64643256ee.js:1:8300)
    at j (polyfills.2ba72d64643256ee.js:1:20943)
    at x (polyfills.2ba72d64643256ee.js:1:21349)
    at HTMLDocument.J (polyfills.2ba72d64643256ee.js:1:21513)

I tried different methods like page reload and javascript win.reload, but the error persisted. Manipulating cy.clock also did not solve the problem.

EDIT: Removing cy.clock() fixed the issue, as it seemed to interfere with time-based operations in the application.

Instead of cy.clock(), I am now using const startTime = new Date().getTime() while keeping everything else unchanged.

Answer №1

Your waitForUpdate method does not appear to be causing the issue, as it simply executes a cy.request() which should not affect the page load.

If you want to avoid synchronization problems, consider moving the cy.reload() outside of the function and using Custom Commands. Here's an example:

Cypress.Commands.add('waitForUpdate', (employeeId, employeeName, employeeEmail) => {

  // code for recursive polling, without cy.reload()

})

it('run the test', () => {
  cy.waitForUpdate(employeeId, employeeName, employeeEmail) 
    .then(() => cy.reload() )

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

Having trouble executing a script in npm to launch testcafe

I'm currently working on a React project where I am utilizing an npm script to run tests using testcafe. These tests involve the use of yargs and shelljs. The issue arises when running the tests through the command npm run test:local -- --api=local, a ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

Dealing with arrays in Typescript and flattening them using the RX

Struggling with a problem involving RXJS transformation in an Ionic 2 application. My goal is to flatten a JSON file into objects, here is the simplified JSON structure: [{ "language": "it", "labels": { "name": "Hi", }, "t ...

What is the most effective way to compare two arrays of objects in JavaScript?

I'm working on a function that needs to return an array of elements based on certain filters. Here is the code for the function: filter_getCustomFilterItems(filterNameToSearch: string, appliedFilters: Array<any>) { let tempFilterArray = []; ...

Can you explain the process of type casting an object in TypeScript?

Looking at this example, I am pondering how to convert an Object into an interface (or a class): interface Person { firstName: string; lastName: string; } var obj={firstName:"James", lastName:"Bond"} as Person; console.log(type ...

Transforming Typescript Strings into ##,## Format

As I've been using a method to convert strings into ##,## format, I can't help but wonder if there's an easier way to achieve the same result. Any suggestions? return new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, max ...

Jest - managing parent class methods during unit tests

The code snippet provided demonstrates a class called First extending TelemetryFramework with specific props and states, containing a method named getData. This method retrieves confidential data and logs telemetry information. However, running unit tests ...

Service Class utilizing Express, Knex, and Objection for enhanced functionality

I'm currently in search of a solution for using BaseService to handle common methods for Objection models. While it works well with UserService, I'm looking to implement some additional methods in the BaseService class. base.service.ts class Bas ...

Leveraging Vue.js as a development dependency in a TypeScript project

I am currently working on a .net core project where all client-side scripts are written in TypeScript. I have a desire to incorporate Vue.js into the TypeScript codebase. Below are snippets of the necessary configurations: tsconfig.json { "compilerOpti ...

Webdriver will automatically open a file as soon as the download is complete

I am currently creating tests and utilizing the Firefox webdriver along with a FirefoxProfile to download a file from an external source. However, I need to be able to read this file immediately after it has finished downloading in order to extract specifi ...

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

Make sure that the 'router-outlet' is a valid Angular component before verifying its presence in the module for Angular 12

Recently, I delved into learning angular with a focus on implementing lazy loading in my project. Here's how the implementation unfolds: Appmodule -- home -- login Homemodule features -- main component Featuresmodule chilrensmodeul childrensmodul ...

Experiencing a problem with the bundle.js file in Angular Universal

My Angular build is giving me this error in the web browser: Uncaught SyntaxError: expected expression, got '<' in bundle.js When I run the command npm run dev:ssr, no errors are generated. However, when I try to access the application, the ...

The Index Module in Ionic 2 is missing the export for the SqlStorage member

Currently, I am utilizing Ionic 2 and attempting to work with SqlStorage to generate queries. However, it seems that the import is not functioning properly. Here is what I have: import {Storage, SqlStorage} from '@ionic/storage'; Unfortunately ...

Tips for creating an instance of a generic function type in TypeScript with a const arrow function

I am encountering an issue with TypeScript where I defined a function type, but I am unable to instantiate it. The strange thing is that the structure works perfectly fine without type arguments and for generic signatures that do not use 'key of' ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Angular is giving me an undefined Array, even though I clearly defined it beforehand

I've been working on integrating the Google Books API into my project. Initially, I set up the interfaces successfully and then created a method that would return an Array with a list of Books. public getBooks(): Observable<Book[]>{ ...

What happens when a CSS module is exported as an empty object?

My go-to for creating projects is using TypeScript and create-react-app. I recently incorporated the typings-for-css-modules-loader and dabbled in css-modules as well. { test: /\.css$/, use: [ require.resolve('style-loader'), { ...

Using Typescript with Angular 2 to Implement Google Sign-In on Websites

Currently, I am in the process of creating a website that utilizes a typical RESTful web service to manage persistence and intricate business logic. To consume this service, I am using Angular 2 with components coded in TypeScript. Instead of developing m ...