【发布时间】:2019-12-27 13:22:27
【问题描述】:
我正在尝试在 iframe 中查找元素,但它不起作用。
有没有人有一些系统可以在 iframe 中使用 Cypress 运行测试?一些进入 iframe 并在那里工作的方法。
【问题讨论】:
标签: automation automated-tests cypress
我正在尝试在 iframe 中查找元素,但它不起作用。
有没有人有一些系统可以在 iframe 中使用 Cypress 运行测试?一些进入 iframe 并在那里工作的方法。
【问题讨论】:
标签: automation automated-tests cypress
这适用于我在本地和通过 CI。图片来源:Gleb Bahmutov iframes blog post
export const getIframeBody = (locator) => {
// get the iframe > document > body
// and retry until the body element is not empty
return cy
.get(locator)
.its('0.contentDocument.body').should('not.be.empty')
// wraps "body" DOM element to allow
// chaining more Cypress commands, like ".find(...)"
// https://on.cypress.io/wrap
.then(cy.wrap)
}
spec file:
let iframeStripe = 'iframe[name="stripe_checkout_app"]'
getIframeBody(iframeStripe).find('button[type="submit"] .Button-content > span').should('have.text', `Buy me`)
【讨论】:
这是here 提到的一个已知问题。您可以创建自己的自定义 cypress 命令来模拟 iframe 功能。将以下功能添加到您的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));
});
});
那么你可以这样使用它:
cy.get('#iframe-id')
.iframe('body #elementToFind')
.should('exist')
此外,由于 CORS/同源策略的原因,您可能必须在 cypress.json 中将 chromeWebSecurity 设置为 false(将 chromeWebSecurity 设置为 false 允许您访问嵌入在应用程序中的跨域 iframe并且还可以导航到没有跨域错误的任何超级域。
这是一种解决方法,它在本地对我有用,但在 CI 运行期间不起作用。
【讨论】:
这是正确的。赛普拉斯不支持 iframe。这很简单,目前不可能。您可以关注(并投票)这张票:https://github.com/cypress-io/cypress/issues/136
【讨论】: