如何在赛普拉斯中断言JavaScript对象?

时间:2020-09-09 05:31:06

标签: javascript node.js automation cypress

我正在尝试获取一个span标记的文本并将其更改为number,然后对该数字使用断言 这是我的command.js文件:

function num(){
  // this is the span text "Published August 27th, 2020"
  cy.get("span_text").then(function($el){
    var actualText = $el.text() 
    var split = actualText.split(" ")
    var year = split[split.length - 1];
    var x =  parseInt(year)
    return cy.wrap(x); // 2020
  })
}

Cypress.Commands.add('year', num)

这就是我在测试文件上调用它,然后使用断言的方式:

// test.js
const newProject = cy.year().then((value) => value
     console.log(value) // 2020 -> OK
);

console.log(newProject) // [Object] here is my question, why is an Object in here ??? I expect to be be a same as 2020

expect(newProject).to.be.greaterThan(2019) // expected [object Object] to be a number or a date

但是我在赛普拉斯日志上收到此错误消息:

expected [object Object] to be a number or a date

我发现我不能断言对象而不是数字。但是我不知道如何用另一个数字来断言该对象的返回值。谁能帮助我,让我知道我的考试有什么问题,我该如何解决呢?

1 个答案:

答案 0 :(得分:0)

在此代码段中,您将Promise分配给newObject。诺言本质上是您正在执行的任何异步命令(在这种情况下为year()的“跟踪器”)。不幸的是,仅从then返回的值不会将其分配给newObject

有两种获取期望值的方法:

  1. 将您的主张移至“然后”:
cy.year().then((value) =>
     expect(value).to.be.greaterThan(2019)
);

  1. 使用async/await
const assertYear = async () => {
    const newProject = await cy.year();
    expect(newProject).to.be.greaterThan(2019);
};

assertYear();