首页 > 解决方案 > 自定义命令中的赛普拉斯常量/变量

问题描述

我有以下用于 cypress 自定义命令的代码,用于生成用户会话 cookie:

   Cypress.Commands.add('getSession', (email, password) => {
        return cy.request({
            url: 'xxx',
            method: 'POST',
            body: {
                email,
                password,
            }
        })
        .then((response) => {
            let body = (response.body);
            expect(response.status).to.eq(200);
            cy.log('Id - ' + body.customerId);

            let session = "SESSIONID=" + body.Cookies.SESSIONID + ";" ...
            cy.log('raw session data - ' + session)

            //Base64 encode
            cy.writeFile('tmp/rawStr.txt', session, 'utf8');
            cy.readFile('tmp/rawStr.txt', 'base64').then((cookie) => {
                cy.log('base64 string - ' + cookie);
            });
        })
    });

我想在另一个自定义命令中重新使用“cookie”中的值,但是每当我运行测试时,它都会说 cookie 未定义。我在该测试中所做的只是创建一个 Cookie 标头,其中包含我在上述步骤中创建的 base64 字符串。

有问题的自定义命令如下所示:

Cypress.Commands.add('createThing', (name) => {
        return cy.request({
            url: 'xxx',
            method: 'POST',
            headers: {
                'Cookie' : 'client_token=' + cookie,
                'Content-Type' : 'application/json'
            },
            body: {
                'name' : name
            }
        })
        .then((response) => {
            let body = (response.body);
            expect(response.status).to.eq(200);
            cy.log(body);
        });
    });

如何获取自定义命令来共享该 cookie 值?

我的规范文件调用自定义命令,如下所示:

/// <reference types="Cypress" />

    describe('deletes a user thing', function() {
      it('create a thing via the api', function() {
        cy.getSession('xxxx', 'xxxxx')
        cy.createThing('thing')
      })
    })

标签: javascriptcypress

解决方案


我建议拆分为 2 个自定义命令。第一个将获得一个coockie,并返回它,另一个方法将重用第一个的结果。就像是:

// Method to get coockie
Cypress.Commands.add('getCookie', (email, password) => {
  cy.request({
      url: 'xxx',
      method: 'POST',
      body: {
          email,
          password,
      }
  }).then((response) => {
    expect(response.status).to.eq(200);
    let cookie = response.body.Cookies
    return cookie
    })
})

// Method to get sessionId that will reuse getCoockie method
Cypress.Commands.add('getSession', (email, password) => {
  cy.getCookie(email, password).then(cookie => {
    let session = "SESSIONID=" + cookie.SESSIONID + ";"
    return session
  })
})

// test
describe('test', () => {
  it('bla bla', () => {
    const email = 'test@test.com'
    const pass = 'pass'
    cy.getSession(email, pass).then(session => {
      console.log(session)
    })
  })
})

推荐阅读