Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store date in some variable in Cypress

Can anyone help me how to store date from a field to variable. Here is the HTML which I am looking at:

<input id="date" class="input_date" id="XYZ" type="date" value="2019-01-12" on_input="table()">

I tried:

const date1 = Cypress.moment(). get('#id_value') 
like image 516
user29496 Avatar asked Nov 20 '25 15:11

user29496


2 Answers

If the ID's are unique, you could try getting the val into a variable as below. I have used date id in the below code.

note: In the input html tag there two ID's, may be need to confirm with dev team which one to be used here

 cy.get('#date').invoke('val').then((val)=>{
   const dateValue = val;
   console.log("Here is the date:"+dateValue);
 })
like image 58
soccerway Avatar answered Nov 23 '25 07:11

soccerway


Although Cypress imports the moment library, there are no built in commands for it that allow chaining, but you can add a custom command to make it easier.

The toMoment() command must be chained off a previous selecting command like cy.get() or cy.contains(). It returns a moment object which you can then use invoke to call all the methods moment provides, and further chain .should() to test the value returned from those methods.

For example,

Spec

Cypress.Commands.add('toMoment', {prevSubject: true}, (element) => {
  return Cypress.moment(element[0].value);
});

it('input tests with moment', () => {

  cy.visit('./app/moment-with-input.html');

  cy.get('input').toMoment()
    .invoke('isValid')
    .should('eq', true);

  cy.get('input').toMoment()
    .invoke('format', 'dddd')
    .should('eq', 'Saturday');

  cy.get('input').toMoment()
    .invoke('diff', Date(2020, 2, 5), 'days')
    .should('eq', -391);

})

HTML fragment (put in '/app' folder of project)

<input id="date" class="input_date" id="XYZ" type="date" value="2019-01-12" on_input="table()">
like image 36
Richard Matsen Avatar answered Nov 23 '25 05:11

Richard Matsen