Cypress 多环境配置

566 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第4天,点击查看活动详情

本文主要目标是完成 Cypress 多环境的配置,以方便我们在不同环境中,快速的切换测试

前期准备

|-- node_modules
|-- cypress
|--|-- e2e                  			// [新增] 相比之前,新增了 e2e 文件夹
|--|--|-- 1-getting-started     	// [新增] 示例数据 1
|--|--|-- |-- todo.cy.js     			// [新增] 示例数据 1 下的测试用例
|--|--|-- 2-advanced-examples    	// [新增] 示例数据 1
|--|--|-- |-- actions.cy.js       // [新增] 示例数据 2 下的测试用例 actions
|--|--|-- |-- ...						      // [新增] 示例数据 2 下其他的测试用例
|--|-- fixtures             			
|--|--|-- example.json      			
|--|-- support              			
|--|--|-- commands.js       			
|--|--|-- e2e.js            			
|-- cypress.config.js       			
|-- package.json
|-- package-lock.json

整理配置文件

在测试的时候,我们经常会分 dev 环境, uat 环境,prod 环境等,针对这些不同的环境,我们想通过不同的 npm 命令就就可以切换环境

大致罗列一下这几个环境的不同点:

  • baseUrl 不同,即浏览器的地址不同
  • backendUrl 不同,即后端连接的地址不同
  • user info 不同,不同环境可能有不同的用户名和密码
  • 其他一些不同配置

改造配置文件

目前 Cypress 使用 cypress.config.js 文件获取配置,那么我们是否可以通过类似 dev.config.jsuat.config.jsprod.config.js 这样子的文件,来针对不同的环境进行配置呢?

拆分公共的配置文件

将公共的配置文件单独列出来,方便维护。创建 configs/common.config.js 文件,然后将通用配置,到处为 CommonConfig,以方便在其他地方使用

// path: configs/common.config.js
// Cypress 的一系列配置: https://docs.cypress.io/guides/references/configuration#Actionability

const CommonConfig = {
    numTestsKeptInMemory: 50,
    // port: null,
    reporter: "spec",
    reporterOptions: null,
    watchForFileChanges: true,

    // 超时 Timeout
    defaultCommandTimeout: 4000, // 重试超时时间
    execTimeout: 60000,
    taskTimeout: 60000,
    pageLoadTimeout: 60000,
    requestTimeout: 5000,
    responseTimeout: 300000,

    // 文件夹 / 文件相关
    screenshotsFolder: "cypress/screenshots",
    videosFolder: "cypress/videos",

    // 可视视图
    viewportHeight: 768,
    viewportWidth: 1440,

    retries: { runMode: 1, openMode: 1 }, // 失败之后,重试 1次

    video: false, // 不保存视频
};

module.exports = CommonConfig;

创建 dev.config.js

cypress.config.js 名称修改为 dev.config.js,然后导入 CommonConfig

// path: dev.config.js
const { defineConfig } = require("cypress");
// 使用 require 引入进来
const CommonConfig = require("./configs/common.config.js");

module.exports = defineConfig({
  // 然后在此处使用
  ...CommonConfig,
  e2e: {
    // baseUrl: "http://dev/frontend/path",
    baseUrl: "https://cn.bing.com/", // 我们在 dev 使用 bing 进行测试
    env: {
      username: "",
      password: "",
      backendUrl: "http://dev/backend/path",
    },
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
  },
});

同理,添加 uat.config.jsprod.config.js

拷贝 dev.config.js,修改其中 baseUrl 分别为 https://www.so.com/https://www.google.com/

// path: uat.config.js
const { defineConfig } = require("cypress");
const CommonConfig = require("./configs/common.config.js");

module.exports = defineConfig({
  ...CommonConfig,
  e2e: {
    // baseUrl: "http://uat/frontend/path",
    baseUrl: "https://www.so.com/", // 修改这一行
    env: {
      username: "",
      password: "",
      backendUrl: "http://uat/backend/path",
    },
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
  },
});

// path: prod.config.js
const { defineConfig } = require("cypress");
const CommonConfig = require("./configs/common.config.js");

module.exports = defineConfig({
    ...CommonConfig,
    e2e: {
        // baseUrl: "http://prod/frontend/path",
        baseUrl: "https://pansoso.com/", // 修改这一行
        env: {
            username: "",
            password: "",
            backendUrl: "http://prod/backend/path",
        },
        setupNodeEvents(on, config) {
            // implement node event listeners here
        },
    },
});

修改 package.json 文件

// path: package.json

{
  "name": "cypress-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "npx cypress open --config-file dev.config.js",   // 修改此处,增加 dev 配置文件
    "uat": "npx cypress open --config-file uat.config.js",   // 修改此处,增加 uat 配置文件
    "prod": "npx cypress open --config-file prod.config.js", // 修改此处,增加 prod 配置文件
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {},
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "cypress": "10.11.0"
  }
}

再次运行

至此,即已经完成了多环境的配置,只需要针对不同的环境,进行个性化的配置即可,当然 CommonConfig 是可以被覆盖的。

npm run dev

// 显示如下信息,且能正常打开,则代表成功
> cypress-test@1.0.0 dev /Users/xx/Desktop/cypress-test
> npx cypress open --config-file dev.config.js

「延伸」写个简单的例子

使用上面的三个环境,我们写一个搜索 cypress 的小例子。

新建文件 search/search.cy.js,然后编写如下代码:

// path: cypress/e2e/search/search.cy.js

/// <reference types="cypress" />
describe('测试搜索 cypress', () => {
    beforeEach(() => {
        // 导航到 baseUrl
        cy.visit('/')
    })

    it('输入 "cypress" 进行搜索', () => {
        cy.get('input[name="q"]').first().type('cypress{enter}')
    })
})

点击测试用例

如图:打开 E2E Testing 测试之后,会看到下面多了一个search/search.cy.js 的测试用例,我们点击即可运行

npm run dev

npm run uat

npm run prod