使用 cypress 测试自定义 HTTP 标头

Mir*_*ert 6 cypress

我尝试用 cypress 构建测试。我需要为测试设置一个 cookie 和一个自定义标头字段。

使用curl,这很容易,例如:

curl -H "aut: BeUser1"  --cookie "aut=BeUser1" ....
Run Code Online (Sandbox Code Playgroud)

但我不知道谁在cypress中设置 header 和 cookie:

cy.setCookie("aut", "BeUser1")
cy.visit("/some/foo");
Run Code Online (Sandbox Code Playgroud)

soc*_*way 7

您可以尝试一下您的案例吗?创建一个login()内部的commands.js 并用于cy.request()登录系统并添加标头。另外before测试,我已经按照给定的方式运行了设置的 cookiecy.setCookie("cookie", "your cookie details here");

Cypress.Commands.add("login", () => {
  cy.request({
    method: 'POST',
    form: true,
    url: 'your-url-here',
    headers: {
      'Content-Type': 'text/html',  
      'aut'    : 'BeUser1',       
    },
    body: {       
      "email": "your email",
      //"username": "your username", depends upon your system login you could use email or username
      "password": "your password",
    }
  }).then(response => {
    const target = response.body.email;
  })

})
Run Code Online (Sandbox Code Playgroud)

后来在测试中我用它cy.getCookie('cookie')来产生cookie。

describe('Set header and cookie', function() { 
  before('set cookie',function(){
  cy.setCookie("cookie", "add your your cookie here");
  });
    it.only('tests login', function() {
      cy.login();
      cy.getCookie('cookie')
      .then((cookie) => {
          console.log(cookie);
       })
     })
  })
Run Code Online (Sandbox Code Playgroud)