如何在Cypress中获取多个别名的值而不引入回调地狱? [英] How to get values of multiple aliases without introducing callback hell in Cypress?

查看:194
本文介绍了如何在Cypress中获取多个别名的值而不引入回调地狱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想检索两个赛普拉斯别名的值,并在测试用例中使用它。我该怎么做而不以下列方式嵌套它们?

Say I want to retrieve the values of two Cypress aliases and use it in my test case. How do I do so without nesting them in the following manner?

cy.get('@alias1')
    .then((alias1) => {
        cy.get('@alias2').then((alias2) => {
            someFunctionThatUsesBothAliases(alias1, alias2);
        })
    })


推荐答案

您可以执行以下操作:

You can do this:

it('test', () => {
    cy.wrap('foo').as('foo');
    cy.wrap('bar').as('bar');
    cy.wrap('baz').as('baz');

    const values = [];
    cy.get('@foo').then( val => {
        values.push(val);
        return cy.get('@bar');
    }).then( val => {
        values.push(val);
        return cy.get('@baz');
    }).then( val => {
        values.push(val);
        someFunc(...values);
    });
});

或者您可以使用我拼凑的这个帮助程序(将其放入您的支持/index.js ):

Or you can use this helper I cobbled together (put it in your support/index.js):

const chainStart = Symbol();
cy.all = function ( ...commands ) {
    const _           = Cypress._;
    const chain       = cy.wrap(null, { log: false });
    const stopCommand = _.find( cy.queue.commands, {
        attributes: { chainerId: chain.chainerId }
    });
    const startCommand = _.find( cy.queue.commands, {
        attributes: { chainerId: commands[0].chainerId }
    });
    const p = chain.then(() => {
        return _( commands )
            .map( cmd => {
                return cmd[chainStart]
                    ? cmd[chainStart].attributes
                    : _.find( cy.queue.commands, {
                        attributes: { chainerId: cmd.chainerId }
                    }).attributes;
            })
            .concat(stopCommand.attributes)
            .slice(1)
            .flatMap( cmd => {
                return cmd.prev.get('subject');
            })
            .value();
    });
    p[chainStart] = startCommand;
    return p;
}

并像这样使用它:

it('test', () => {

    cy.wrap('one').as('one');
    cy.wrap('two').as('two');
    cy.wrap('three').as('three');

    cy.all(
        cy.get(`@one`),
        cy.get(`@two`),
        cy.get(`@three`)
    ).then( values => {
        someFunc(...values);
    });
});

这篇关于如何在Cypress中获取多个别名的值而不引入回调地狱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆