如何在Cypress中获取多个别名的值而不引入回调地狱?

用户名

假设我要检索两个赛普拉斯别名的值,并在测试用例中使用它。如何不按以下方式嵌套它们?

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

你可以这样做:

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

或者,您也可以使用我拼凑的这个帮助程序(将其放入您的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);
    });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章