比较两个值并在赛普拉斯中做出决定

时间:2019-12-13 07:27:30

标签: compare ui-automation cypress

因此,我在页面上有两个值需要比较,并根据结果执行一些操作。

//First Block
cy.get('selctor1').invoke('text').then(somevalue => {
    cy.get('selector2').should('have.text', somevalue).then(() => {
        #Do Something when equal
    })
})

//Second Block
cy.get('selctor1').invoke('text').then(somevalue => {
    cy.get('selector2').should('not.have.text', somevalue).then(() => {
        #Do Something when not equal
    })
})

因此对于肯定值,当两个值相等时,一切正常。但是对于两个值不相等的情况,它仅检查第一个块并失败。我应该怎么做才能在值不相等而不是第一个块时执行第二个块?

1 个答案:

答案 0 :(得分:1)

对不起,第一次不清楚。这是我编辑过的答案:

然后vs应该

请尽量避免使用thenthen是不可重复的,并且会引起意想不到的行为。 但是should也会引入异常行为。

错误使用then 的示例:

describe("asd", () => {
    it("fails but retries", () =>{
        console.log("######### first test")

        cy.wrap({ fn: () => console.log(new Date())})
        .invoke("fn")
        .should(r => expect(r).to.eq(true));
    })


    it("fails but retries not", () =>{
        console.log("######### next test")

        cy.wrap({ fn: () => console.log(new Date())})
        .invoke("fn")
        .then(r => {
            expect(r).to.eq(true)
        });
    })
})

在此示例中,您两次看到相同的代码,但是第一个块使用should,而第二个块使用then。断言必须失败,但是在第一个块中,将重复断言。打开DEV COnsole,可以看到第一个块重试了很多,而第二个块没有重试。

这就是“意外”行为的意思。假设您wrap a object that is dynamically extended (maybe by a UI action) and you are expecting a property on this object. In the second block (然后) the UI acton must be executed very fast and before the然后is executed so that the期望`不会失败。

should情况下,您还有4秒的时间(如果`defaultCommandTimeout没有被覆盖),直到断言最终失败。

should的用法错误:

describe("ad", () => {
    it("test", () => {
        cy.visit("https://www.cypress.io/")
        cy.get("*[aria-label='pricing']")
            .invoke('text').should(someValue => { 
                cy.get("asdad", {timeout: 5000}).should("not.exist");
            })
    })
})

您期望什么?绿色测试?不,该测试失败:

enter image description here

为什么会这样?因为get引入了隐式断言“应该存在”(请参阅​​:https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Default-Assertions)。

带有回调的

Should会跳过默认的断言(请参阅:https://docs.cypress.io/api/commands/should.html#Notes)。我认为他们通过按标志切换来跳过它。这可能会导致标志再次反转,从而迫使赛普拉斯即使使用should not exist也会检查“ asdad”是否确实存在。

这些东西有一个问题:https://github.com/cypress-io/cypress/issues/5963

我不知道为什么cy.log具有您在案例中提到的行为。因此,如果您想在回叫中使用then命令,则可以使用cy,或者避免使用cy命令,而将should与显式断言一起使用({{1 }。也许在解决该问题之后,也可以使用expect

旧答案

cy.log

您可以将 cy.get('selctor1').invoke('text').should(someValue => { const $el = Cypress.$('selector2'); if ($el.text() ==== someValue) { // positive expect().... } else { // negative expect().... } }) 与回调一起使用。只要达到超时或没有断言失败,就会执行此回调(和上一个should命令)。 您始终可以使用原始jQuery对象进行处理。这取决于您是否需要在invoke期间执行cypress的所有检查。

如果您需要进一步的帮助,请告诉我。