简体   繁体   中英

Cypress compare two strings

I have an h1 tag in HTML that contains the actual time (year, month, day and time) updated each 6 seconds and it works. I need to check that after six seconds the time is changed. The problem is that I tried the following code:

  var t1;
  cy.get("h1").should(($d) => {
    t1 = $d.text();
    });
    cy.wait(600);
    cy.get("h1").should(($d) => {
        const t2 = $d.text();
        expect(t2).not.equal(t1);
    })

But the first variable (t1) is always an empty string "", while the second one take the time. The test passes but for the wrong reason ("" is different from "2021-11-09 10:52:33") How can I take also the first time?

Update
I tried to show only the first timestamp, and it works with this code:

  cy.get("h1").should(($d) => {
    const t1 = $d.text();
    expect(t1).not.equal("");
    })

But I need to compare it with the second one, not with the empty string. I think it is because Cypress is async, but I don't know how to connect the second part.

I solved the problem using var for each timestamp and not const. With var it can take both timestamp and compare them:

  var t1;
  var t2;
  cy.get("h1").should(($d) => {
    t1 = $d.text();
    expect(t1).not.equal("");
    })
    
    cy.wait(6000);
    cy.get("h1").should(($d) => {
        t2 = $d.text();
        expect(t2).not.equal(t1);
    })

It works only if I check for the first timestamp that is different from "", I don't really know why, but it's okay because in this way I verify that the timestamp works. In addition 6 seconds are 6000 and not 600 ms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM