Skip to content

[Cypress] 如何將變數設定到 Cypress.env?

Published: at 11:07 AM (2 min read)

在寫 Cypress 測試時,時常會遇到不同環境需要傳遞不同的登入資訊或一些資料變數到測試中的情況,這時候有哪些方法呢?

Cypress 設定 env(環境變數)有幾種不同的方式:

如何將變數設定到 Cypress.env

📍 以下方式可以單獨或組合使用,而且是有優先順序的:

  1. 測試中動態設定:最高優先級,會覆蓋其他設定。
  2. CLI 參數:次高優先級,會覆蓋環境變數cypress.env.json
  3. 環境變數 CYPRESS_ 前綴:會覆蓋 cypress.env.jsoncypress.config.js 中的設定。
  4. cypress.env.json 檔案:會覆蓋 cypress.config.js 中的設定。
  5. cypress.config.jscypress.config.ts 中設定:最低優先級。

1. 測試中動態設定

Cypress.env("apiUrl", "https://api.example.com");
Cypress.env("username", "testuser");
Cypress.env("password", "testpass");

2. CLI 參數

npx cypress run --env apiUrl=https://api.example.com,username=testuser,password=testpass

3. 環境變數 CYPRESS_ 前綴

export CYPRESS_apiUrl=https://api.example.com
export CYPRESS_username=testuser
export CYPRESS_password=testpass

4. cypress.env.json 檔案中設定

{
  "apiUrl": "https://api.example.com",
  "username": "testuser",
  "password": "testpass"
}

5. cypress.config.jscypress.config.ts 中設定

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  env: {
    apiUrl: "https://api.example.com",
    username: "testuser",
    password: "testpass",
  },
});

💁‍♂️ 以上設定後,皆可以順利在測試中使用 Cypress.env("apiUrl") 來取得 apiUrl 的值

describe("Example Test", () => {
  it("should use environment variables", () => {
    cy.request(Cypress.env("apiUrl")).then(response => {
      expect(response.status).to.eq(200);
    });
  });
});

參考資料


Previous Post
[LeetCode] 647. Palindromic Substrings
Next Post
[GCP] 如何利用 GCP free-tier 建立免費的 n8n 自動化伺服器