首页 > 解决方案 > 无法将 autoId 值获取到 jobId 对象中,这里 localStorage autoId 是一个字符串

问题描述

无法将 autoId 值获取到jobId对象中,这里的 localStorageautoId是一个字符串。有人可以在这里就问题提出建议吗?我正在尝试根据 jobId 查找表行并检查是否jobRow [columnPosition] == value断言它......

注意:我正在尝试尽可能优化和减少代码行。

  let tableDatacy = "Reports_Table";
  let columnName= "Customer";
  let checkCase = "should";
  let value  = "Main Customer";
  let jobId = {};
  
  const columnPosition = Cypress.$(`[data-cy=${tableDatacy}]`)
      .find(`th:has(a:contains(${columnName}))`)
      .index()
  console.log("Get the silly index !: "+columnPosition)

  cy.getLocalStorage('autoId').then(autoId => jobId = autoId.jobId);
  let jobRow = Cypress.$(`[data-cy=${tableDatacy}] > tbody > tr :contains(${jobId})`);

  if (checkCase === "should" && jobRow [columnPosition] ==  value){
    result = "true";
    expect(result).to.include("true");
  } else if (checkCase === "should not" && jobRow.length == 0) {
    result = "false";
    expect(result).to.include("false");
  }

在此处输入图像描述

标签: jquerycypress

解决方案


你有一个异步行,其余的都是同步的,所以任何依赖jobId都应该放在.then().

否则,同步代码将在异步行完成之前全部运行。

const columnPosition = Cypress.$(`[data-cy=${tableDatacy}]`)
    .find(`th:has(a:contains(${columnName}))`)
    .index()
console.log("Get the silly index !: "+columnPosition)

// Make async call and everthing that needs the result 
// must be inside the callback

cy.getLocalStorage('autoId').then(autoId => {

  jobId = autoId.jobId

  // let jobRow = Cypress.$(`[data-cy=${tableDatacy}] > tbody > tr :contains(${jobId})`);
  let jobRow = Cypress.$(`[data-cy=${tableDatacy}] > tbody > tr:has(td:contains(${jobId}))`);

  // if (checkCase === "should" && jobRow [columnPosition] ==  value){
  const jobRowText = Cypress.$(jobRow).find('td').eq(columnPosition).text()
  if (checkCase === "should" && jobRowText === value) {
    result = "true";
    expect(result).to.include("true");
  // } else if (checkCase === "should not" && jobRow.length == 0) {
  } else {
    result = "false";
    expect(result).to.include("false");
  }

});

选择行

所以tr :contains(${jobId})

意思是“给我tr那个包含的孩子jobId,结果是td

tr:has(td:contains(${jobId}))

意思是“给我tr那个td包含jobId”。


选择行中的列并比较文本

jobRow不是数组,它是一个元素,因此您需要使用更多的 jQuery 来提取要比较的文本。

const jobRowText = jobRow.find('td').eq(columnPosition).text()
if (checkCase === "should" && jobRowText === value) {

或结合

let jobRowText = Cypress.$(`[data-cy=${tableDatacy}] > tbody > tr:has(td:contains(${jobId}))`)
  .find('td').eq(columnPosition).text()

赛普拉斯命令方式

cy.contains('[data-cy=${tableDatacy}] > tbody > tr', jobId)
  .find('td').eq(columnPosition)
  .invoke('text')
  .then(jobRowText => {

    if (checkCase === "should" && jobRowText === value) {
      result = "true";
      expect(result).to.include("true");
    } else {
      result = "false";
      expect(result).to.include("false");
    }
  })



推荐阅读