【问题标题】:Cypress.io + TypeScript. Assertion call in beginning of testCypress.io + TypeScript。测试开始时的断言调用
【发布时间】:2018-08-08 15:01:26
【问题描述】:

我是 Cypress.io 和 TypeScript 的新手。所以这里有些东西我没看懂。

我的代码:

//Test
describe('TEST description', function () {
it('newJobCreation', function () {
    //Some code 1
    var numberBefore = cy.get('#idOfItem')
    var _numberBefore = +numberBefore
    //Some code 2

    var numberAfter = cy.get('#idOfItem')
    var _numberAfter = +numberAfter
    //Assertion
    expect(_numberBefore-1).equals(_numberAfter) //Same result if I use: assert.equal(_numberBefore-1, _numberAfter)
   }) 
})

让我们说_numberBefore after //一些code2被改变并变成_numberAfter。我想断言这个数字减少了 1。

在 Cypress.io 中运行测试后,我收到错误消息:

预计 NaN 等于 NaN

它失败了。

问题:

为什么我的断言在所有代码执行后没有调用?为什么在测试开始时调用它?

【问题讨论】:

    标签: typescript assertion browser-automation cypress


    【解决方案1】:

    赛普拉斯一次将所有命令异步排队。这意味着

    let elem = cy.get("#elem");
    // attempt to do something with returned element...
    

    不会工作。 cy.get() 只是告诉赛普拉斯将get() 命令添加到最终要运行的命令列表中。它不会立即运行命令。

    .then() 提供了一个不错的选择 - 您可以使用它来排队一些 Javascript,以便在命令运行时运行,如下所示:

    cy.get("#elem1").then(elem1 => {
        // elem1 is the underlying DOM object.
    
        // You can put regular javascript code here:
        console.log("This will happen when the queued .then() command is run");
    
        // You can also put more Cypress commands here, like so:
        cy.get("#elem2").should(elem2 => {
            expect(elem1.someProperty).to.equal(elem2.someProperty);
        });
    });
    

    请注意,.should(() => {}) 的行为类似于 .then(),除非它会在任何包含的断言失败时重试。

    请参阅here 了解有关将两个元素的值相互比较的更多信息,并参阅this doc page 了解有关赛普拉斯中异步命令队列的一般概念的更多信息。

    【讨论】:

    • 一切正常,例如代码必须是这样的:cy.get('#idOfItem').then(($numberBefore) =>{ const txt = $numberBefore.text() var _numberBefore = +txt //Some code 1 cy.get('#idOfItem').should(($numberAfter) => { const txt2 = $numberAfter.text() var _numberAfter = +txt2 expect(_numberBefore-1).to.equal(_numberAfter) }) })变量需要在“()”括号中。附:感谢您的帮助。
    • 如果您谈论的是() => {} 匿名函数样式,someVar => {} 实际上是有效的。如果没有参数,或者有多个参数,则需要括号,但如果只有一个参数,则可以省略 ()。有关工作示例,请参阅 this fiddle
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    相关资源
    最近更新 更多