integration-testing - 如何在 Cypress 中获取多个别名的值而不引入回调 hell ?

标签 integration-testing cypress

假设我想检索两个 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);
    });
});

关于integration-testing - 如何在 Cypress 中获取多个别名的值而不引入回调 hell ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55298710/

相关文章:

cypress - 使用 cypress 选择 react 选择下拉列表选项

cypress - 使用 Cypress 绕过 UI 登录

c# - 使用测试数据库集成测试链式 WCF 服务

c++ - 假 FTP 服务器

ruby-on-rails - 运行Rspec功能规范时如何抑制来自请求的噪音?

vuejs2 - 跨浏览器平台测试

cypress - 如何在柏树中登录文件?

ruby-on-rails - 捆绑 rspec/spec 失败

ruby-on-rails - 无法命中数据库,通过 minitest 集成测试

html - 等待 DOM 加载 : Cypress