cy.wrap().its()... 当 .its() 中的值包含句点时不起作用

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

我希望从我正在使用 Cypress 测试的当前 URL 中提取 URL 参数。我基本上能够从this SO post得到答案,但是,当我使用 Cypress 的 .its() 命令时,我提取的值不可用。
url 中的参数都有句点,我相信这就是我的错误的原因。 这是我正在构建的自定义 Cypress 命令:

Cypress.Commands.add('getParmsCommand', function(value) {
cy.url().as('url')

cy.then( () => {
  cy.log(this.url)
  const kvPairArray = this.url.toString().split('?')[1].toString().split('&')
  const paramObj = {}
  kvPairArray.forEach(param => {
    cy.log(param)
    //default 'value' to 0 if it doesn't exist
    const [ key, value="0" ] = param.split('=')
    paramObj[key] = value
  })
  //forcefully adding a debug element to the key value store for testing
  paramObj['beverage'] = 'soda'

cy.wrap(paramObj)
  .its('timeline.ws')                                   //doesn't work
  // .its(`${Cypress.$.escapeSelector('timeline.ws')}`) doesn't work
  // .its('timeline\.ws')                               doesn't work
  // .its('"timeline.ws"')                              doesn't work
  // .its('beverage')                                   this DOES work!
  .then(parmVal => {
    cy.log(parmVal)
})

这是我尝试从中提取的 URL 的相关部分:

timeline.ws=3600000&timeline.to&timeline.fm&timeline.ar=false

从错误中可以看出,Cypress 只查找 id timeline,而不是 timeline.ws;它完全忽略句点之后的所有内容,因此永远找不到我的参数。

我在 2018 年就看到 Cypress 的 .get() 函数存在类似的错误。

javascript cypress special-characters cypress-custom-commands
1个回答
2
投票

.its()
只是属性提取的简写。由于它因句点而失败,因此您可以在
.then()
中使用方括号表示法。

cy.wrap(paramObj)
  .then(paramObj => paramObj['timeline.ws'])

或者只是

cy.wrap(paramObj['timeline.ws'])

使用 URL 构造函数

const urlString = 'http://example.com?timeline.ws=3600000&timeline.to&timeline.fm&timeline.ar=false'
const url = new URL(urlString)

cy.wrap(url.searchParams.get('timeline.ws'))
  .should('eq', '3600000')

cy.wrap(url.searchParams.get('timeline.to'))
  .should('be.empty')

cy.wrap(url.searchParams.get('timeline.ar'))
  .should('eq', 'false')
© www.soinside.com 2019 - 2024. All rights reserved.