# 准备工作

  1. 首先将 Cypress 安装到前端作为开发依赖项
npm install --save-dev cypress
  1. 然后在 package.json 中添加 scripts 字段,用于运行测试
"scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint .",
    "preview": "vite preview",
    "server": "json-server -p3001 --watch db.json",
    "test": "vitest run",
    "coverage": "vitest run --coverage",
    "cypress:open": "cypress open" // 添加
  },
  1. Cypress 测试在运行时不会启动系统,需要在后端添加 npm-script ,在测试模式下启动它
"scripts": {
    "start": "cross-env NODE_ENV=production node index.js",
    "dev": "cross-env NODE_ENV=development nodemon index.js",
    "test": "cross-env NODE_ENV=test jest --verbose --runInBand",
    "start:test": "cross-env NODE_ENV=test node index.js" // 添加
  },
  1. 以测试环境运行后端,并使用专属的测试数据库
npm run start:test

# 开始测试

  1. 当前后端都在运行时,用以下命令启动 Cypress
npm run cypress:open
  1. 在 Cypress 中,选择 E2E ,选择 Chrome ,然后创建一个 test.cy.js 文件
  2. 就可以开始测试了
    笔记测试代码
describe('template spec', function (){
  beforeEach(function() {
    cy.visit('http://localhost:5173') // 登录
  })
  it('front page can be opened', function() {
    cy.contains('Notes') // 查找是否有 Notes
  })
  // it('user can login', function () {
  //   cy.contains('login').click()
  //   cy.get('#username').type('root')
  //   cy.get('#password').type('salainen')
  //   cy.get('#login-button').click()
  // })
  describe('when logged in', function() {
    beforeEach(function() {
      cy.contains('login').click() // 点击登录
      cy.get('#username').type('root') // 获得用户名输入框后输入用户名
      cy.get('#password').type('salainen') // 获得密码输入框后输入密码
      cy.get('#login-button').click() // 点击登录按钮
    })
    it('a new note can be created', function() {
      cy.contains('New note').click()
      cy.get('input').type('a note created by cypress')
      cy.contains('save').click()
      cy.contains('a note created by cypress')
    })
  })
})
更新于 阅读次数