工具 – Cypress

发布时间 2023-08-02 12:40:40作者: 兴杰

介绍

Cypress 是一款 e2e 测试工具。每当我们写好一个组件或者一个页面之后,我们会想对整体做一个测试。

在不使用工具的情况下,我们会开启 browser,然后做一系列点击、滚动、填 form 等等交互,然后观察看看是否全部运行正常,这就是 e2e 测试。

而借助 Cypress,我们可以把这套测试流程写成代码封装起来。让它变成自动化测试。若以后代码修改了,我们就不需要人工测试(费劲)。

 

参考

YouTube – Cypress in a Nutshell

Docs – Get Started

 

Cypress 环境

Cypress 的环境是独立于我们程序的。我们甚至可以用 Cypress 测试别人的程序,比如测试 google.com

Cypress 基于 Node.js,只要 Node.js 就可以了,不需要 Webpack、Vite 之类的。

当然我们也可以把 Cypress 和我们的程序放到一块。它们也不冲突。

 

Get Started

create project

创建一个项目。这里我用 Vite TypeScript。你可以用其它的,Cypress 只要有 Node.js 就可以了。

写一个简单的页面

.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form autocomplete="off">
    <input name="firstName" placeholder="First Name" required>
    <input name="lastName" placeholder="Last Name">
    <button>Submit</button>
    <p class="thank-you">Thank you! We have received your enquiry.</p>
  </form>
  <script type="module" src="./home.ts"></script>
</body>

</html>
View Code

.scss

@use '../module/reset';

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  form {
    min-width: 320px;

    display: flex;
    flex-direction: column;
    gap: 16px;

    input {
      border-radius: 4px;
      border: 1px solid black;
      padding: 16px;
    }

    button {
      border-radius: 4px;
      background-color: pink;
      color: red;
      padding: 20px;
      font-size: 20px;
      text-transform: uppercase;
      letter-spacing: 1px;
    }

    .thank-you {
      line-height: 1.5;

      &:not(.shown) {
        display: none;
      }
    }
  }
}
View Code

.ts

import './home.scss';

document.querySelector('form')!.addEventListener('submit', e => {
  e.preventDefault();
  document.querySelector('.thank-you')!.classList.add('shown');
});
View Code

运行

yarn run vite

效果

install cypress

yarn add cypress --dev

添加 cypress 到 tsconfig.json

"compilerOptions": {
  "types": [
    "cypress"
  ]
},

如果是 vite 的话,inclde 也需要添加 cypress folder

运行

yarn run cypress open

它会打开一个 App

进入 E2E Testing。

for 第一次,它会创建一些 folder and file

folder and file

选一个 browser 做测试

创建第一个 test file

文件的位置

write test

describe('test form', () => {
  it('common use', () => {
    cy.visit('https://192.168.1.152:4200/src/home/home.html'); // 访问我们的程序页面
    cy.get('.thank-you').should('not.be.visible'); // 检查 thank you message 必须是 hidden
    cy.get('input[name="firstName"]').type('Derrick'); // 查找 input firstName 输入 'Derrick'
    cy.get('input[name="lastName"]').type('Yam');
    cy.get('button').click(); // 点击 submit
    cy.get('.thank-you').should('be.visible'); // 检查 thank you message 必须是 shown
  });
});

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

第一次会添加 Cypress 需要的 folder and file 到项目里。

进入 E2E Testing 选择一个 browser。第一次会提示你创建第一个 test file。

测试文件在 e2e folder 里。

这是我的测试页面

写好 HTML、TS 后 yarn run  vite 跑起来。