【问题标题】:Can Cypress test if a control is Pristine?赛普拉斯可以测试控件是否为 Pristine 吗?
【发布时间】:2018-07-25 14:42:36
【问题描述】:

我正在开发一个 Angular 4 应用程序,我们正在使用 Cypress 进行前端/集成测试。 在我们的一个表单上,我们有一个取消按钮,它可以清除子表单上的所有输入并重置表单。 我想知道赛普拉斯有什么方法可以检查表单或控件是否原始,还是我需要检查输入的内容是否全部清除? (我知道如何做后者,但宁愿能够使用 Pristine 进行检查,也不愿遍历所有控件)。

这是我目前正在做的事情:

cy.get('[data-test=cancelButton]').click();
cy.get('[data-test=referenceField').should('be.empty');
cy.get('[data-test=referenceField').should('have.attr', 'placeholder', 'Numbered list number');

我只想做类似的事情

cy.get('[data-test=cancelButton]').click();
cy.get('[data-test=referenceField').should('be.pristine');

【问题讨论】:

    标签: angular typescript cypress


    【解决方案1】:

    赛普拉斯允许您创建custom child commands。这是基本语法:

    Cypress.Commands.add('shouldBePristine', {
        prevSubject: true // this allows it to be chained off another command
    }, (subject /*, arg1, arg2, ...*/) => {
        // subject is whatever is wrapped by the Cypress object that
        // .shouldBePristine() is called on
    
        // In your case, you would do something like this:
        expect(subject).to.be.empty;
        expect(subject).to.have.attr('placeholder', 'Numbered list number');
    
        // This command does not need to change the subject for the next function
        // in the chain, so we will just return what was passed in
        return subject;
    });
    

    然后你会这样调用你的命令:

    cy.get('[data-test=referenceField]').shouldBePristine();
    

    您也可以write a custom chai helper,但这个过程看起来要复杂得多。

    【讨论】:

    • 我认为编写自定义命令是可行的方法,但是当我尝试执行 subject.should(... 时,我收到错误 cypress_runner.js:141523 TypeError: subject.should is not a function。这是subject 在控制台中查看时的内容。 [input.ng-untouched.ng-pristine.ng-invalid, prevObject: jQuery.fn.init(1), context: document, selector: "[data-test=createNumberListReference]"]
    • @red_dorian Doh,那是我的错。 subject 是底层包装对象,而不是赛普拉斯包装器,因此您需要一个 Chai 断言。我通常会仔细检查我的答案,但这次我忘记了。对于那个很抱歉!我已经编辑了我的答案。如果它仍然不适合你,请告诉我。
    • 值得注意的是,Cypress 命令实际上不能在自定义命令中调用。刚刚调试我的答案时,我发现了这一点。
    • 它有帮助,并且绝对为我指明了正确的方向。检查.empty 和占位符适用于输入字段,但不是多种输入类型或具有默认值的字段的通用解决方案。 expect(subject).to.have.value(subject[0].defaultValue)适用于后者。但这是我的问题的问题,而不是你的答案。我将您的答案标记为解决方案,并将在我自己的功能上工作,并将其作为单独的帖子包含在此处。感谢您的帮助。
    • 非常感谢!很高兴我能帮上忙。
    猜你喜欢
    • 2021-11-14
    • 2020-10-26
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2021-10-20
    相关资源
    最近更新 更多