Cypress - run test in iframe

后端 未结 3 1914
日久生厌
日久生厌 2021-01-22 03:49

I\'m trying to find elements in iframe but it doesn\'t work.

Is there anyone who have some system to run tests with Cypress in iframe? Some way to get in iframe and work

3条回答
  •  旧巷少年郎
    2021-01-22 04:24

    It's a known issue mentioned here. You can create your own custom cypress command which mocks the iframe feature. Add following function to your cypress/support/commands.js

    Cypress.Commands.add('iframe', { prevSubject: 'element' }, ($iframe, selector) => {
      Cypress.log({
        name: 'iframe',
        consoleProps() {
          return {
            iframe: $iframe,
          };
        },
      });
      return new Cypress.Promise(resolve => {
        resolve($iframe.contents().find(selector));
      });
    });
    

    Then you can use it like this:

    cy.get('#iframe-id')
      .iframe('body #elementToFind')
      .should('exist')
    

    Also, because of CORS/same-origin policy reasons, you might have to set chromeWebSecurity to false in cypress.json (Setting chromeWebSecurity to false allows you to access cross-origin iframes that are embedded in your application and also navigate to any superdomain without cross-origin errors).

    This is a workaround though, it worked for me locally but not during CI runs.

提交回复
热议问题