Cypress测试登录页面

800 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情

这篇文章将通过Cypress官方提供的案例,介绍一下测试典型登录页面的思路及cy.request()指令的使用

Ready?

Cypress官方提供了适用于不同场景的多种案例,比如引入第三方库、标签跳转、网络拦截等,非常适合拿来学习,在开始之前,首先介绍一下本文中用到官方案例的打开方式

  1. 选择自己喜欢的方式把案例仓库cypress-example-recipes拉取到本地

  2. 进入到logging-in__html-web-forms文件夹,运行npm start启动项目

  3. 最后在对应端口就可以访问页面了:

Go!

测试登录页面的业务流

  • 访问页面
  • 点击输入框输入姓名
  • 点击输入框输入密码
  • 点击提交按钮
  • 用户密码正确,跳转到展示页面;不正确就显示错误信息

与上述流程对应的代码如下:

describe("HTML form submission", function () {
  const username = "jane.lane";
  const password = "password123";
  
  beforeEach(function () {
    cy.visit("/login");
  });

  it("错误的登录信息", function () {
    cy.get("input[name=username]").type("jane.lae");
    cy.get("input[name=password]").type("password123{enter}");

    // 显示提示信息
    cy.get("p.error")
      .should("be.visible")
      .and("contain", "Username and/or password is incorrect");

    // 仍在登录页面
    cy.url().should("include", "/login");
  });

  it("正确的登录信息", function () {
    cy.get("input[name=username]").type(username);
    cy.get("input[name=password]").type(password);
    cy.get("form").submit();

    // 跳转到/dashboard页
    cy.url().should("include", "/dashboard");
    cy.get("h1").should("contain", "jane.lane");

    // 成功等录后会在浏览器中添加cookie
    cy.getCookie("cypress-session-cookie").should("exist");
  });
});

image.png

  • 使用cy.visit()访问页面的缺点👉每次访问页面都需要重新加载全部资源,增加了测试时间

  • 更优雅的做法👉使用cy.request()直接向真实浏览器接口发送请求,代码如下:

describe("HTML form submission with cy.request", function () {
  const username = "jane.lane";
  const password = "password123";
  it("can bypass the UI and yet still test log in", function () {
    cy.request({
      method: "POST",
      url: "/login",
      form: true, //设置 Content-Type: application/x-www-form-urlencoded headers
      body: {
        username,
        password,
      },
    });
    cy.getCookie("cypress-session-cookie").should("exist");
  });
});

  • 通过 cy.request() 发出的请求本质上是通过Cypress Test RunnerNode中发出HTTP请求