赛普拉斯常量/自定义命令中的变量

时间:2019-11-19 14:07:10

标签: 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值?

我的spec文件如下调用自定义命令:

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

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

1 个答案:

答案 0 :(得分:0)

我建议拆分为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)
    })
  })
})