在寫 Cypress 測試時,時常會遇到不同環境需要傳遞不同的登入資訊或一些資料變數到測試中的情況,這時候有哪些方法呢?
Cypress 設定 env(環境變數)有幾種不同的方式:
如何將變數設定到 Cypress.env?
📍 以下方式可以單獨或組合使用,而且是有優先順序的:
- 測試中動態設定:最高優先級,會覆蓋其他設定。
- CLI 參數:次高優先級,會覆蓋環境變數和
cypress.env.json。 - 環境變數
CYPRESS_前綴:會覆蓋cypress.env.json和cypress.config.js中的設定。 cypress.env.json檔案:會覆蓋cypress.config.js中的設定。cypress.config.js或cypress.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.js 或 cypress.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);
});
});
});