Web applications 我想在Cypress中使用InnerText值进行进一步计算

Web applications 我想在Cypress中使用InnerText值进行进一步计算,web-applications,ui-automation,cypress,Web Applications,Ui Automation,Cypress,因此,我能够获得元素的innerText值,但我希望全局使用该值。我尝试使用以下代码: cy.get('#selector').invoke('text').then(text => { const price = text; }); 在测试的其余部分,我如何访问price的值?另外,值是字符串,如何将其更改为整数 据我所知,只有在该功能中才能使用固定价格。您需要使其全球化/模块化 describe('name of your test', () => { let pri

因此,我能够获得元素的innerText值,但我希望全局使用该值。我尝试使用以下代码:

cy.get('#selector').invoke('text').then(text => {
const price = text;
});

在测试的其余部分,我如何访问price的值?另外,值是字符串,如何将其更改为整数

据我所知,只有在该功能中才能使用固定价格。您需要使其全球化/模块化

describe('name of your test', () => {

    let price = null;

    before(()=>{

        cy.get('#selector').invoke('text').then(text => {
             price = new Number(text);
        });        

    })

});

您可以通过在
commands.js
文件中创建一个函数并在每个测试中调用它来实现这一点。 在commands.js文件中,创建一个“simplePrice()”函数,如下所示:

Cypress.Commands.add('simplePrice', () => {
    cy.get('#selector').invoke('val').then(val => {
        const price = val;
        return price;
      })
});
然后在每个测试中,您可以得到如下价格值。这种方式的好处是,您可以多次拨打电话以获取价格值。还将其作为一个公共函数保留,当您在一个地方(即commands.js)进行更改时,所有测试都会收到更改

describe('Test to get the price value', ()=>{  
    it('Test-1', () => {
        cy.simplePrice().then((val)=>{
            const price_first = val;
            console.log("Hello log this one:"+price_first);  
        })  
    })

    it('Test-2', () => {
        cy.simplePrice().then((val)=>{
            const price_second = val;
            console.log("Hello value this second time:"+price_second);
        }) 
    })

})

当我打印price变量时,该值为空。问题是变量price的范围。即使使用文本,价格的值也是正确的,但它是有限的。我想在测试中使用变量的值。更新了我的答案这也不起作用,因为价格值仅在cy.get命令函数中可用。但是我希望它能被测试中的其他函数使用,我没有完全理解。你是说下面的测试代码
cy.get('#selector').invoke('text')。然后(text=>{const price=text;})写在commands.js文件中?当我们写这个
cy.get('#selector').invoke('text')。然后(text=>{const price=text;cy.log(“Print total:+total);})我们得到了total的值,一切都很完美,但是如果我们写这个
cy.get('#selector').invoke('text')。然后(text=>{const price=text;});cy.log(“打印总计:+总计”)未定义total的值,因为它在全局范围内不可用。