Is it possible to receive some leeway in terms of timing for the current moment?

I am currently working with the dayjs function and would like to make some adjustments to the "time now" functionality in order to prevent my test from failing if it takes longer than a minute to complete. Here is what I have at the moment;

const dayjs = require('dayjs');
const timeNow = dayjs().format("H:mm");
cy.get('#dateTime').contains(timeNow)

However, I am interested in exploring ways to introduce a 2-3 minute buffer into the timeNow constant (for example, if timeNow is recorded at 9:30, I would like to accept any time between 9:27 and 9:33) as the test fails half of the time when it does not reach that step within the minute.

Answer №1

If you want to ensure that your time-related tests are extremely reliable, consider utilizing the cy.clock() command. This will effectively halt the app's clock, ensuring the accuracy of any time values retrieved.

This means that even if there are delays in your test execution, the time value obtained from dayJs will remain accurate and consistent throughout.

One important factor to be mindful of is when the time value is actually set within the element. If the app makes API calls to update the time display, it is crucial to strategically capture the timeNow value to avoid discrepancies.

Although your query lacks detail, refer to the documentation for a better understanding. The example provided in the documentation offers clarity.

cy.clock()
cy.visit('/index.html')
cy.tick(1000)
cy.get('#seconds-elapsed').should('have.text', '1 seconds')
cy.tick(1000)
cy.get('#seconds-elapsed').should('have.text', '2 seconds')

Furthermore, using .contains() may not be the most suitable approach for this scenario. As you need to dynamically select elements based on the variable timeNow, opting for .should() with a within assertion would be more appropriate.

cy.get('#datetime')
  .invoke('parseInt')
  .should('be.within', timeNow, timeNow + 60000)

It is essential that the timeNow value is numerical to achieve accurate comparisons.

Answer №2

If you need to verify the time being 9:27, 9:28, or 9:29, consider utilizing a oneOf assertion.

cy.get('#dateTime')
  .then($el => {
    return $el.text().split(' ')[1]  // "16/07/2024, 12:30" -> "12:30"
  })
  .should('be.oneOf', ['9:27' '9:28', '9:29']) 

However, relying solely on this approach may not be optimal as there could be timing discrepancies. Using the clock command is recommended as a more reliable option.

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

Purge the inversify-js container and fetch fresh service instances

My frontend application in react-native utilizes inversify-js for service classes. I have implemented an IOC structure where services are shared as singleton instances, each with an init/destroy method to manage internal state. While the init/destroy mec ...

What is the process to enable mandatory validation after a change in input in Angular 4?

Currently, I am working on a project using Angular 4. One of the tasks I need to achieve is validation. <input [(ngModel)]="someModel" required placeholder="some placeholder"/> The validation triggers immediately, but I want it to only trigger aft ...

Guidelines for defining an Interface based on the value of another argument

Imagine a scenario where... interface Group { name: string isPublic: boolean } interface User { id: string age: number } type EntityType = 'group' | 'user' function doTask(type: EntityType, entity: Group | User): bool ...

What is the proper way to use Object.entries with my specific type?

On my form, I have three fields (sku, sku_variation, name) that I want to use for creating a new product. I thought of converting the parsedData to unknown first, but it seems like a bad practice. export type TProduct = { id: string, sku: number ...

Verify that the password is entered correctly in Angular2

My Angular2 form looks like this: this.registerForm = formBuilder.group({ 'name': ['', Validators.required], 'email': ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+&bso ...

Combining Angular 2 and Sails.js for Ultimate Web Development

Looking to integrate Sails with Angular 2 and add TypeScript to my project. As a newcomer in this field, I'm unsure how to configure this. I have created a Sails app using the command: sails new myApp Could anyone guide me on how to incorporate thi ...

The index access type cannot be used with T[Key extends keyof T]

My work frequently involves arrays structured like this: [ {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}] and I often need to convert them into a dictionary/map format, for example: ...

The error occurred due to an invalid regular expression when trying to create a route with route parameters

In my development process, I have a specialized class for creating routes and another class for bundling these routes before adding them to an express app or router. However, I encountered a problem with my route class when I attempted to create a route wi ...

How can I utilize a callback in TypeScript when working with interfaces?

Can someone guide me on how to implement an interface in typescript with callback function? interface LoginCallback{ Error: boolean, UserInfo: { Id: string, OrganizationId: string } } interface IntegrationInterface { Ini ...

What is the process for retrieving a string value from a URL?

Here is the link to my page: http://localhost:4200/#/home/jobmanager/status Can someone help me figure out how to extract the "status" from the URL as a string in TypeScript (.ts file)? For example: this.getJobs("STATUS_HERE"); I need to replace "STATU ...

How can you export the type of a private class in TypeScript without exporting the class itself?

I am facing a dilemma in my module where the public method of a public class is responsible for creating and returning a new instance of a private class. The stipulation is that only MyClass should have the capability to instantiate MyClassPrivateHelper. ...

Strategies for distributing a single lit-element instance among multiple web components

With numerous web components stored in individual repositories, I am seeking a way to share a single instance of lit-element/lit-html across all of them in order to optimize bundle size. Rather than having a separate instance in each bundle. To achieve th ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

What are the benefits of pairing Observables with async/await for asynchronous operations?

Utilizing Angular 2 common HTTP that returns an Observable presents a challenge with nested Observable calls causing code complexity: this.serviceA.get().subscribe((res1: any) => { this.serviceB.get(res1).subscribe((res2: any) => { this.se ...

Communicating with an ASP.NET Controller using Angular2: A Step-by-Step Guide

I am working with a controller that includes a Create action. The main purpose of this action is to receive a name and data from a file form, and then return a list of files using the IndexViewModel. public class HomeController : Controller { static L ...

Upon refreshing the page, Vuex encounters an issue where it is unable to read

My website has a Navbar component that utilizes values from the Vuex store. Prior to entering each route, I trigger a dispatch from Vuex as shown below: router.beforeEach((to, from, next) => { //... store.dispatch("updateUserData"); ...

Issue encountered with the props type upon import, Ts(2322)

Seeking assistance with a TypeScript, StyledComponent, and React project using Create React App. Encountering an error during build time that cannot be ignored. // browser and terminal error TypeScript error in ./src/index.tsx(4,1): Type '{ alt: ...

Ways to conceal the side menu upon logging out in Ionic 2

I have successfully implemented login and logout functionality in my project. The issue I am facing is that after logging out, the side menu is still visible. How can I hide the side menu automatically after logout and redirect to the home page? https://i ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

Developing Placeholder Model in Angular

I am currently working on creating a sample model in Angular to fetch data from the backend. However, I am encountering an error related to arrays. abc.ts export class abc { date: Date; time: string; ABC_Info: [{ item: string, ...