Choose a date range from the date picker

I am currently attempting to combine two dates using a rangepicker.

Below is the command used to select the date:

Cypress.Commands.add('setDatePickerDate', (selector, date) => {
  const monthsShort = [
    'janv.',
    'févr.',
    'mars',
    'avril',
    'mai',
    'juin',
    'juil.',
    'août',
    'sept.',
    'oct.',
    'nov.',
    'déc.',
  ];
  const month = monthsShort[date.getMonth()];
  const day = date.getDate();
  const year = date.getFullYear();
  cy.getBySel(selector).should('not.be.disabled');
  cy.getBySel(selector).click();
  // selecting year
  cy.get('.mantine-CalendarHeader-calendarHeaderLevel').click();
  cy.get('.mantine-DatePicker-calendarHeaderLevel').click();
  recurse(
    () => cy.get('.mantine-YearsList-yearsListCell').invoke('text'),
    (n) => {
      if (!n.includes(year)) {
        cy.get('.mantine-DatePicker-calendarHeaderControlIcon').first().click();
        return false;
      }
      cy.get('.mantine-YearsList-yearsListCell').contains(year).click();
      return true;
    },
    {
      limit: 12,
    }
  );
  // selecting month
  cy.get('.mantine-MonthsList-monthsListCell').contains(month).click();
  // selecting day
  cy.get('.mantine-DatePicker-day')
    .contains(new RegExp(`^(${day})`))
    .click();
});

This is the code snippet from my test:

    cy.setDatePickerDate(
      'filter-date',
      new Date('2021-07-01'),
      new Date('2021-07-05')
    );

The issue I am facing is that only the date 2021-07-01 is being populated in the date field and not the other one.

Could you please provide any guidance on what mistake I might be making?

//updated question as the cy.getBySel(selector).click(); is an optional part

Cypress.Commands.add('setDatePickerDate', (date, clickOnDatePicker) => {
    const monthsShort = [
      'janv.',
      'févr.',
      'mars',
      'avril',
      'mai',
      'juin',
      'juil.',
      'août',
      'sept.',
      'oct.',
      'nov.',
      'déc.',
    ];
  if(clickOnDatePicker) {
    cy.clickOnDatePicker(clickOnDatePicker);
  }
  cy.wrap(date).each((date) => {
  const month = monthsShort[date.getMonth()];

//rest of the code remains the same

Command for clickOnDatePicker:

Cypress.Commands.add('clickOnDatePicker', (clickOnDatePicker) => {
  cy.getBySel(clickOnDatePicker).click()
});

My d.ts file:

setDatePickerDate(object: { clickOnDatePicker?: string }, date: Date): void;

Test code snippet:

cy.setDatePickerDate({ clickOnDatePicker: 'filter-date' }, [
      new Date('2021-07-18'),
    ]);

The test is failing with the error message:

Syntax error, unrecognized expression: [data-testid=Sun Jul 18 2021 04:00:00 GMT+0400 ()]

I wish to execute the below code if a selector needs to be clicked:

cy.setDatePickerDate({ clickOnDatePicker: 'filter-date' }, [
      new Date('2021-07-18')]);

otherwise, if there is no selector to click:

cy.setDatePicker([{ new Date('2021-07-18')], new Date[('2021-07-18')]);

Answer №1

Perhaps creating a custom command as an external layer can help manage the complexity of dealing with different parameters?

By using a spread operator like ...args, you can avoid passing parameters with brackets [] or braces {}. The spread operator converts the parameters into an array for easier handling.

I have included cy.log() to demonstrate that the arguments are being correctly parsed.

Cypress.Commands.add('pickDate', (date) => {
  // This section only includes the logic for selecting a single date, which can be independently tested
})

Cypress.Commands.add('setDatePicker', (...args) => {

  if (typeof args[0] === 'string') {
    const selector = args[0]
    cy.log('Selector', selector)
    cy.getBySel(selector).should('not.be.disabled');
    cy.getBySel(selector).click();
  }

  const dates = args.filter(arg => typeof arg !== 'string')
  dates.forEach(date => {
    cy.log(date.toUTCString())
    cy.pickDate(date)
  })
})

it('handles a selector and two dates', () => {
  cy.setDatePicker('filter-date', new Date('2021-07-01'), new Date('2021-07-05'))
})
it('handles two dates', () => {
  cy.setDatePicker(new Date('2021-07-01'), new Date('2021-07-05'))
})
it('handles a single date', () => {
  cy.setDatePicker(new Date('2021-07-05'))
})
it('handles three dates', () => {
  cy.setDatePicker(new Date('2021-07-01'), new Date('2021-07-05'), new Date('2021-07-07'))
})

This log confirms that each type of parameter list variation is being correctly managed

https://i.sstatic.net/SUKgz.png

Answer №2

Your specialized command does not currently support passing in multiple dates. One workaround is to execute the command twice:

cy.setDatePickerDate('filter-date', new Date('2021-07-01');
cy.setDatePickerDate('filter-date', new Date('2021-07-05');

Alternatively, you have the option to modify your custom command to accept an array of dates.

Cypress.Commands.add('setDatePickerDate', (selector, dates) => {
  cy.wrap(dates).each((date) => {
    // code to execute
  });
});

cy.setDatePickDate('filter-date', 
                   [new Date('2021-07-01'), new Date('2021-07-05')]
);

Edit: In response to the query, "how do I conditionally check if the selector is disabled and only click then?"

...
cy.getBySel(selector).then(($el) => {
  if ($el.prop(':disabled')) { // Applying JQuery to prevent test failure if the element is not disabled.
    cy.wrap($el).click();
  }
});
...

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

Understanding the Class Syntax in Node.js

I'm having trouble understanding how to retrieve the value from a Node JS Class [Trying to use [Symbol.iterator '']]alert(Hello, ${this.name}!); Is there another way to approach this? class User { name = "Anonymous"; sayHi() { ...

Is there a way to adjust the text color based on whether a value is negative?

I am currently developing a web application that performs addition operations on integers. Within this application, I have implemented two functions named num1() and num2() to retrieve the integers provided by the user for calculation. My objective is to m ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

jQuery technique for loading images

Here is the issue at hand: I am attempting to utilize jQuery to accelerate image loading on my webpage. To achieve this, I have a code snippet specifying an initial image that should be replaced with another image once the page has finished loading. < ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

Can someone help me troubleshoot this issue with my code so that my website can open in a blank page using about:blank?

I'm currently facing an issue while trying to make one of the pages on my website open with an about:blank URL upon loading. Despite embedding the code in my index.html file, it doesn't seem to be functioning properly. Here's the code I&apos ...

Executing API calls utilizing Axios in a NodeJS environment with the Authorization Basic feature

I have developed an API to retrieve a token from PayPal. curl -v POST https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "CLIENT_ID:SECRET" &b ...

Struggling with deploying Next.js on Vercel

Encountered an issue while trying to deploy a project on Vercel. The error message is as follows: fileName: comps/Navbar.js imported as import Navbar from "./Navbar"; 16:36:51 ModuleNotFoundError: Module not found: Error: Can't reso ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

What steps should I take to resolve the textarea border bottom CSS effect?

My simple border bottom animation is working fine with a basic input element, but it's not functioning properly when used with a textarea. (If using JavaScript is necessary for a solution, please provide guidance) How can I adjust the height of a te ...

The child component is failing to detect changes, consider using alternative methods like ngDoCheck to update the component's value

Within the childComponent @input() method, I am sending an array of objects where each object has 3 properties: name, id, and selected (boolean). My goal is to change only the selected property in the array and pass it to the child component for rendering. ...

Steps to remove a script upon clicking a button?

On my website, I have integrated a plugin called manychat using a <script>. However, when I click on the Drawer Cart, the manychat symbol overlays over the checkout button, which is not visually appealing. Is it possible to unload this script when ...

An endless cascade of dots appears as the list items are being rendered

Struggling to display intricately nested list elements, Take a look at the JSON configuration below: listItems = { "text": "root", "children": [{ "text": "Level 1", "children": [{ "text": "Level 2", "children": [{ "text": ...

Infinite loop caused by Angular JS routing止

I have set up a Django server with the following configuration: urls.py urlpatterns = [ url('^', IndexView.as_view(), name='index') ] landing/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('^.*&a ...

Eliminating the glow effect, border, and both vertical and horizontal scrollbars from a textarea

Dealing with the textarea element has been a struggle for me. Despite adding decorations, I am still facing issues with it. The glow and border just won't disappear, which is quite frustrating. Could it be because of the form-control class? When I rem ...

Guidelines on encoding query parameters for a tRPC query with the fetch function

As stated in the tRPCs official documentation, the query parameters must adhere to this specific format: myQuery?input=${encodeURIComponent(JSON.stringify(input))} Here is an example of a procedure: hello: publicProcedure .input(z.object({ text: z.s ...

Ways to remove newly added tasks using JavaScript function?

I have an existing list of li elements in my HTML that can be deleted using JavaScript. However, whenever I add a new li, the delete function no longer works on the newly added item. I suspect the issue lies within the current implementation of the for loo ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

Clicking on the prop in a React class component

This is the situation I am facing <List> {mainTags.map((mainTagItem) => { return ( <ListItem onClick={() => { setMainTag(mainTagItem.tag.tagId) }} button className={classes.mainTagItem}> <div className={classes. ...

Using AngularJS to retrieve JSON data with the HTTP module

I am a beginner in the world of angularjs and I need some guidance. Below is the code I have written: <!DOCTYPE HTML> <html ng-app="myapp"> <head> <meta charset="utf-8"> <title>Angularjs project</title> <script type= ...