Automated tests io:读取表单输入值并将其存储到JS变量(或常量)中

Automated tests io:读取表单输入值并将其存储到JS变量(或常量)中,automated-tests,forms,cypress,Automated Tests,Forms,Cypress,我在一个简单的页面上有一个HTML表单(非常简单,没有像Ajax这样棘手的部分,…)。我尝试读取任何输入的默认值(type=“text”,同样没有技巧),并将其存储在常量中以供以后使用(assert) HTML看起来像: <form method="post" ...> <input type="text" id="xyz" name="xyz" value="123"> </form> describe('General tests', functio

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

HTML看起来像:

<form method="post" ...>
  <input type="text" id="xyz" name="xyz" value="123">
</form>
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)

    })

  })
})
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)

    })

  })
})
这不管用。但在玩了几个小时之后(在更复杂的测试套件=文件中,这对我来说是偶然的)。我意识到,如果上一个测试(=it())访问与上次访问的URL相同的URL,则此构造将按预期工作。比它像奇迹一样工作

有效的Cypress测试如下所示:

<form method="post" ...>
  <input type="text" id="xyz" name="xyz" value="123">
</form>
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)

    })

  })
})
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)

    })

  })
})
我认为测试应该是独立的,但看起来不是

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

简单的断言,如“cy.get('#id_of_input').should('eq',…)”可以很好地工作,但它不允许我处理输入的默认值(通过测试覆盖)

所以我的问题是:

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


谢谢大家的帮助。

要回答您的问题:


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

您使用它的方式通过异步命令队列绕过了预期的Cypress工作流。如果你不知道我在说什么,我建议你读一下这本书

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

cy.visit('http://localhost/settings');
cy.get('#xyz')。然后(elem=>{
//elem是.get()命令所针对的底层Javascript对象。
常数xyz=Cypress.$(elem).val();
cy.log(xyz);
});
.then()。
允许您将代码排队,以便测试运行程序按照测试顺序运行。有关命令队列和
.then()
的更多信息,请参阅


2) 是的,
描述功能可以相互影响。Cypress单独运行每个文件,但单独的描述只是按照它们排队的顺序运行

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

let message=”“;
描述(“设置值”,()=>{
它(“设置值”,()=>{
message=“hi”;
});
});
描述(“检索值”,()=>{
它(“检索并打印设置值”,()=>{
cy.log(message);//将“hi”记录到Cypress日志窗口
});
});

如果您使用的是typescript,那么可以使用tslint插件cypress来防止类似这样的错误-