我想在 Cypress 中使用 InnerText Value 进行进一步计算

I want to use InnerText Value for further calculation in Cypress

因此,我能够获取元素的 innerText 值,但我想在全局范围内使用该值。我尝试使用以下代码:

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

如何在测试的其余部分访问价格值?另外,该值是一个字符串,如何将其更改为整数?

据我所知,不变价格只会在该功能中可用。你需要做到 global/modular

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

})