简体   繁体   中英

document.getElementById doesn't work in Cypress

I get an error("myDiv is null"), when I try to use document.getElementById in Cypress. Can anybody give me a hint? This is my setup:



a.html
...
<div id='myid'>
</div>
...

test.cy.js

function foo()
{
    let myDiv = document.getElementById('myid');
    let myParagraphs = myDiv.getElementsByTagName('p');
    ...
}


it('MyTest', ()=>   {
        cy.visit('\fsdgjfs\a.html');
        foo();
        ...
        
});

myDiv should be not null.

You are mixing synchronous and asynchronous commands, and it is causing your foo() command to fire before cy.visit() is fired (or completes).

Consider the following two code samples:

it('test', () => {
  cy.visit('https://www.google.com');
  const googleDocument = document;
  expect(googleDocument).to.not.be.null;
});

it('test', () => {
  cy.visit('https://www.google.com')
  .then(() => {
    const googleDocument = document;
    expect(googleDocument).to.not.be.null;
  });
});

The first test will fail, because the googleDocument variable is declared synchronously, before the cy.visit command completes. The second test will pass, because the googleDocument variable is declared inside of an asynchronous cy.then() block, which occurs only after cy.visit() completes.

If you want to find out if mydiv > p exists, the best way is to use cypress-if plugin.

That way you can use Cypress command with full timeout/retry, but branch the test code if your element does or does not exist.

Install

$ npm i -D cypress-if
# or using Yarn
$ yarn add -D cypress-if

Import in /cypress/support/e2e.js

import 'cypress-if'

Test

it('MyTest', ()=> {
  cy.visit('\');
  cy.get('#myid > p')
    .if()
    .log('exists')
    ...                      // commands when exists
    .else()
    .log('does not exist')
    ...                      // commands when not exists
})

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