3

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') 
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user29496
  • 187
  • 1
  • 3
  • 10

2 Answers2

2

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);
 })
soccerway
  • 10,371
  • 19
  • 67
  • 132
  • @user29496 Thats good, ...Please upvote and accept if you are happy:) – soccerway Feb 07 '20 at 14:03
  • @RichardMatsen When you get some time, can you help me with this question https://stackoverflow.com/questions/60880864/token-set-gets-removed-while-running-the-cypress-test – soccerway Mar 27 '20 at 23:28
1

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()">
Richard Matsen
  • 20,671
  • 3
  • 43
  • 77