【问题标题】:check value of parameters in URL with Cypress使用 Cypress 检查 URL 中的参数值
【发布时间】:2021-06-15 09:57:43
【问题描述】:

在我们的工具中,我们创建了一个 url,其中包含一些带有值的参数。我希望赛普拉斯检查这个 url 的内容。

示例网址为: http://someUrl.com/sap/?action=create&type=sw&notifno=70432&repby=TRL&repres=ABC&geo=017&startloc=12345&notiftp=2021-06-15T08:06:42.379Z&scen=1.0&refno=1234567&awsrt=-&vrst=&sbst=&objtp=art&objtxt=&objfc=&tel=084123456&prio=4Niet Emergency&priost=&prioen=&wbi=&facts=&bgeb=AB-CD&bequi=

我已将 url 存储在“href”变量中,但我现在如何检查所有 attr 及其值?我真的不知道。

【问题讨论】:

    标签: javascript cypress


    【解决方案1】:

    我会将其解析为一个对象,然后使用.wrap().its().should() 命令:

    const url = "http://someUrl.com/sap/?action=create&type=sw&notifno=70432&repby=TRL&repres=ABC&geo=017&startloc=12345&notiftp=2021-06-15T08:06:42.379Z&scen=1.0&refno=1234567&awsrt=-&vrst=&sbst=&objtp=art&objtxt=&objfc=&tel=084123456&prio=4 Niet urgent&priost=&prioen=&wbi=&facts=&bgeb=AB-CD&bequi=";
    const arr = url.split('/?')[1].split('&');
    const paramObj = {};
    arr.forEach(param => {
      const [ key, value ] = param.split('=');
      paramObj[key] = value;
    });
    
    cy
      .wrap(paramObj)
      .its('tel')
      .should('eq', '084123456');
    

    或者如果你想断言更多属性:

    cy
      .wrap(paramObj)
      .then(obj => {
        expect(obj.notifno).to.eq('70432');
        expect(obj.tel).to.eq('084123456');
      });
    

    【讨论】:

    • 非常感谢,似乎是一个很好的解决方案。将尽快实施。
    • 不幸的是,我没有让它正常工作。我忘了提到的是参数和值必须是变量,因此我可以在 Cypress 中将场景大纲与 Cucumber 一起使用。
    【解决方案2】:

    我的同事提出了这个解决方案,现在包括 Cucumber 系列:

    Given('I expect the parameter {string} of the SAP-link on dossier {string} to equal {string}',(parameter:string, dossier:string, value:string) => {
        cy.get('selector').each(ele => {
            if(ele.text().trim().indexOf(dossier) == 0) {
                cy.get('selector')
                    .parents('selector')
                    .find('selector').should('have.attr', 'href').then((sapUrl: JQuery<HTMLElement>) => {
                    cy.log(sapUrl.toString());
                    const queryParamString: string = sapUrl.toString().split('?')[1];
                    cy.log(queryParamString);
                    const queryParamArray: string[] = queryParamString.split('&');
                    var params: {} = {};
                    queryParamArray.forEach((keyValueString: string) => {
                        const currentParamArray: string[] = keyValueString.split('=');
                        params[currentParamArray[0]] = currentParamArray[1];
                    });
    
                    // Actual param check
                    expect(params[parameter]).to.equal(value);
                });
            }
        });
    });
    

    【讨论】:

    • 这与@pavelsaman 的代码相同(但不整洁)。
    • @SteveZodiac 是的,你是对的,但我们无法让它发挥作用,因此它有点不同。我们知道,我们还有多余的日志,这些日志是不需要的。
    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 2012-07-28
    • 2023-03-08
    • 2019-12-07
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多