如何在 cypress 12 中授予 Chrome 剪贴板权限

问题描述 投票:0回答:3
cypress clipboard
3个回答
2
投票

如果您使用的是最新的 Cypress 版本 12.9.0,则

invoke()
命令已更改为查询,从而改变了它的工作方式。我认为这导致了你的错误。

你可以用

.then()
代替。

cy.window().its('navigator.clipboard')
  .then((clip) => clip.readText())
  .should('equal', 'Hello World')

同时将 CDP 移到顶部——完整结构:

Cypress.automation('remote:debugger:protocol', {
  command: 'Browser.grantPermissions',
  params: {
    permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
    origin: window.location.origin,
  },
})

cy.visit('https://www.w3schools.com/howto/howto_js_copy_clipboard.asp')

cy.contains('button', 'Copy text').click()

cy.window().its('navigator.clipboard')
  .then((clip) => clip.readText())
  .should('equal', 'Hello World')

0
投票

在 v12.7.0 上,您可以使用以下方式授予剪贴板权限。

cy.window()
  .its('navigator.clipboard')
  .then((clipboard) =>
    cy
      .stub(clipboard, 'writeText')
      .resolves()
      // @ts-ignore
      .as('writeText'),
  )

然后你可以用

检查剪贴板
cy.get('@writeText')
  .should('have.been.calledOnce')
  .its('firstCall.args.0')
  .should('equal', expected)

0
投票

您可以使用

cy.stub()
cy.spy()
捕捉剪贴板活动。

请注意,应用程序还有其他方式与剪贴板交互,因此这仅限于您正在测试的特定页面。

Cypress.automation('remote:debugger:protocol', {
  command: 'Browser.grantPermissions',
  params: {
    permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
    origin: window.location.origin,
  },
})

cy.visit('https://www.w3schools.com/howto/howto_js_copy_clipboard.asp', {
  onBeforeLoad: (contentWindow) => {
    cy.spy(contentWindow.navigator.clipboard, 'writeText').as('writeText')
  }
})
  
cy.contains('button', 'Copy text').click()

cy.get('@writeText')
  .should('have.been.calledWith', 'Hello World')
© www.soinside.com 2019 - 2024. All rights reserved.