Cypress.io:将表单输入的值读取并存储到 JS 变量(或常量)中

Ond*_* M. 3 forms automated-tests cypress

我在一个简单的页面上有一个 HTML 表单(非常简单,没有像 Ajax 这样的棘手部分,...)。我尝试读取任何输入的默认值(type="text",同样没有技巧)并将其存储在常量中以备后用(断言)。

HTML 看起来像:

<form method="post" ...>
  <input type="text" id="xyz" name="xyz" value="123">
</form>
Run Code Online (Sandbox Code Playgroud)

Cypress 测试,不起作用,看起来像:

describe('General tests', function(){

  context('General', function() {

    it('can read the input and store in const', function () {

        cy.visit('http://localhost/settings')
        const xyz = Cypress.$('#xyz').val()
        cy.log(xyz)

    })

  })
})
Run Code Online (Sandbox Code Playgroud)

这不起作用。但是经过几个小时的播放(偶然地,这在更复杂的测试套件 = 文件中对我有用)。我意识到,如果先前的测试( = it() )访问与上次访问的 URL 相同的 URL,则此构造按预期工作。比它像奇迹一样工作。

有效的赛普拉斯测试看起来像:

describe('General tests', function(){

  context('General', function() {

    it('makes magic and allows the next test to work', function () {

        cy.visit('http://localhost/settings')

    })

    it('can read the input and store in const', function () {

        cy.visit('http://localhost/settings')
        const xyz = Cypress.$('#xyz').val()
        cy.log(xyz)

    })

  })
})
Run Code Online (Sandbox Code Playgroud)

我认为测试应该是独立的,但看起来它们不是。

我尝试了其他方法来获取输入信息变量的值,最接近我需要的是使用闭包“.then()”,但它只能用于单个输入,不能用于更复杂的形式。

像 "cy.get('#id_of_input').should('eq', ...)" 这样的简单断言工作正常,但它不允许我使用输入的默认值(并通过测试覆盖)。

所以我的问题:

1)以这种方式使用包含的jQuery来获取输入值并将其存储到常量中是否可以?如果现在我需要为表单中的 5 个不同输入字段执行此操作时的另一种方法是什么(对于信号输入闭包就可以了)2)测试相互影响是否可以?

感谢大家的帮助。

Jos*_*ica 6

回答您的问题:


1)根据文档,Cypress.$是“同步查询元素的好方法”。(强调他们的)

您使用它的方式通过异步命令队列绕过了预期的 Cypress 工作流程。如果您不知道我在说什么,我建议您阅读他们的文档中对 Cypress精彩介绍

我建议将以下内容作为您发布的代码的替代方案:

cy.visit('http://localhost/settings');
cy.get('#xyz').then(elem => {
    // elem is the underlying Javascript object targeted by the .get() command.
    const xyz = Cypress.$(elem).val();
    cy.log(xyz);
});
Run Code Online (Sandbox Code Playgroud)

.then().允许您将代码与测试运行器按顺序运行。见这个答案有关命令排队等详细信息.then()


2) 是的,describe函数之间可以相互影响。Cypress 分别运行每个文件,但单独的描述只是按照它们排队的顺序运行。

例如,以下代码可以正常工作:

let message = "";

describe("Set a value", () => {
    it("Sets a value", () => {
        message = "hi";
    });
});

describe("Retrieve a value", () => {
    it("Retrieves and prints the set value", () => {
        cy.log(message); // Logs "hi" to the Cypress log window
    });
});
Run Code Online (Sandbox Code Playgroud)