在调用链中调用cy.log

问题描述 投票:0回答:1

我正在尝试在 Cypress 调用链中间记录一些内容:

function geAccountElement() {
    return cy.get('div[ui-id=account]')
        .then(thing => {
            cy.log('Peek at thing: ' + thing);
            return thing;
        })
        .contains(testAccountName)
        .parents('div[ui-id=account-card]')
}

但我收到此警告:

Command `contains` expects ["element", "cy"] as a previous subject, but "any" is passed from `then` command

如何使这种可链接的日志记录功能发挥作用?


更新于 2024 年 3 月 23 日星期六,下午 06:20:04

原来我更困惑了。我在 IntelliJ 工具提示中看到了该警告,但没有运行测试。如果我这样做,我会看到:

cy.then() failed because you are mixing up async and sync code.

In your callback function you invoked 1 or more cy commands but then returned a synchronous value.

我想做的是在链式调用之间记录这些内容。我知道我可以做到这一点:

cy.get('div[ui-id=account]')
.invoke('val')
.then(thing => {
    cy.log('Peek at thing: ' + thing);
})  

但这是一个终端操作..意味着测试的其余部分就此停止。我想尝试在

get
contains
之间进行一些日志记录。

cypress cypress-log
1个回答
0
投票

在我的测试中,有关混合异步和同步代码的错误通过像这样包装返回值来修复:

cy.visit('https://example.com');

cy.get('h1')
  .then(thing => {
      cy.log('Peek at thing: ' + thing)   // this is an async command
      // return thing                     // this line is the "sync" value complained about
      return cy.wrap(thing)               // wrapping makes it async
  })
  .contains('Example Domain')

Cypress 对这个错误消息并不太聪明,因为

cy.log()
只是一个副作用,对链主题没有影响(即
return thing
在没有 cy.log 的情况下是可以接受的)。

您可以改为交换同步

Cypress.log()
调用

cy.get('h1')
  .then(thing => {
      Cypress.log({
        message: 'Peek at thing: ' + thing
      })
      return thing
  })
  .contains('Example Domain')

并利用其他属性获取更多信息日志

cy.get('h1')
  .then(thing => {
      Cypress.log({
        displayName: 'Peek at thing:',
        message: thing
      })
      return thing
  })
  .contains('Example Domain')

© www.soinside.com 2019 - 2024. All rights reserved.