我希望从我用Cypress测试的当前URL中提取一个URL参数.我基本上可以从this SO post得到答案,然而,当我使用Cypress 的.its() command时,我提取的值对我来说是不可用的. 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

You can see from the error that Cypress is only looking for the id timeline, NOT timeline.ws; it completely ignores everything after the period, and thus, never finds my parameter. Cypress error message

早在2018年,我就看到有一个similar error with Cypress's .get()的功能.

我对javascript和Cypress都是新手,所以我希望这只是一件我忽略了的奇怪而简单的事情.在这一点上,我们非常欢迎任何建议或有根据的猜测!

谢谢.

推荐答案

.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')

Javascript相关问答推荐

响应式JS DataTable中的Bootstrap 5弹出程序无法正常工作

如何在react + react路由域名中使用DeliverBrowserRouter?

使用JavaScript重命名对象数组中的键

将数据从strapi提取到next.js,但响应延迟API URL

是否有方法在OpenWeatherMap API中获取过go 的降水数据?

通过嵌套模型对象进行Mongoose搜索

colored颜色 检测JS,平均图像 colored颜色 检测JS

用JavaScript复制C#CRC 32生成器

处理时间和字符串时MySQL表中显示的日期无效

连接到游戏的玩家不会在浏览器在线游戏中呈现

Angular 形式,从DOM中删除不会删除指定索引处的内容,但会删除最后一项

使用带有HostBinding的Angular 信号来更新样式?

变量在导入到Vite中的另一个js文件时成为常量.

使用插件构建包含chart.js提供程序的Angular 库?

当代码另有说明时,随机放置的圆圈有时会从画布上消失

AJAX POST在控制器中返回空(ASP.NET MVC)

将嵌套数组的元素乘以其深度,输出一个和

将多个文本框中的输出合并到一个文本框中

在SuperBase JS客户端中寻址JSON数据

我不知道如何纠正这一点.