มา set config file ให้กับ cypress กันเถอะ
สวัสดีฮะ วันนี้ผมจะมาแนะนำการแยก environment ระหว่าง develop server, staging server และ production server ที่ใช้ค่า environment ที่ต่างกัน
ทำไมถึงต้องมีถึงหลาย server ลองเข้าไปอ่านได้ที่นี่
Let’s start !
สร้าง folder สำหรับเจ้าตัว cypress ขึ้นมาแล้วเปิด terminal ในโปรเจ็คนั้น ๆ เลย จากนั้นก็พิมพ์คำสั่งข้างล่างนี้ลงไปเพื่อเป็นการติดตั้งตัว cypress
yarn init
หรือ
npm init
สำหรับคนที่ขี้เกียจกด enter รัว ๆ ก็แนะนำให้ใช้ yarn init -y หรือ npm init -y
จากนั้นก็ติดตั้ง cypress ลงไปในนี้ได้เลย
yarn add cypress
หรือ
npm i cypress
จากนั้นก็เพิ่ม scripts เข้าไฟล์ package.json เพื่อให้ง่ายต่อการเรียกใช้
// package.json"scripts": { "cypress": "cypress"}
จากนั้นก็เปิด cypress ได้เลย
yarn cypress open
หรือ
npm run cypress open
แท่นแท้นนน cypress จะ generate folder สำคัญ ๆ ออกมาให้เอง พร้อมท้ังเปิด cypress gui มาให้ใช้งาน แต่เราจะเขียนไฟล์ test ของเราขึ้นมาเองนะฮะ จะลบทิ้งหรือเก็บไว้อ่านเล่นก็ได้ แต่ผมขอลบมันทิ้งไปละกันจะได้ดูโล่ง ๆ ดี
rm -rf cypress/integration/examples
touch cypress/integration/test.spec.js
จากนั้นเราจะเขียนคำสั่งง่าย ๆ ให้มัน
ณ ที่นี้ถ้าเราเอาไปรันเลยมันจะพัง เพราะว่าเรายังไม่ได้ set up ค่า environment ให้กับมันนะฮะ วิธีการเซ็ตก็ง่าย ๆ ให้ไปแก้ที่ไฟล์ cypress.json
// cypress.json{
"baseUrl": "https://google.co.th", "env": { "server": "dev" }
}
แต่ แต่ แต่ ถ้าเราไป set up แบบนี้มันจะทำให้เวลาเราไปรันบน server อื่น ๆ ที่ไม่ใช่ dev server มันจะทำให้เราต้องมาแก้ environment หรือเอาไป set up ci เวลา deploy ไม่ได้ เพราะฉะนั้นเราจึงต้องสร้างไฟล์ config มาให้มันเรียกใช้ใน environment ที่ต่างกัน โดยเอาคำสั่งข้างล่างไปใส่ไว้ที่ plugin ของ cypress ได้เลย
จากนั้นเราก็ต้องสร้างไฟล์ config ไว้ภายใต้ cypress
mkdir cypress/config
touch cypress/config/dev.json
touch cypress/config/staging.json
touch cypress/config/prod.json
จากนั้นก็เอา environment ของเราไปวางไว้ในส่วนของ dev ได้เลยย
// cypress/config/dev.json{ "baseUrl": "https://google.co.th", "env": { "server": "dev" }}
อันนี้เป็นของ staging
// cypress/config/staging.json{ "baseUrl": "https://www.youtube.com/", "env": { "server": "staging" }}
และอันนี้ก็เป็นของ production
// cypress/config/prod.json{ "baseUrl": "https://facebook.com", "env": { "server": "production" }}
สุดท้ายก็ไป set up script ของ package.json เพื่อให้ง่ายต่อการเรียกใช้นะฮะ
// package.json"scripts": { "cypress": "cypress", "cypress:openDev": "cypress open --env configFile=dev", "cypress:openStage": "cypress open --env configFile=staging", "cypress:openProd": "cypress open --env configFile=prod"}
สุดท้ายมาลองเช็คกันดู
yarn cypress:openStage
yarn cypress:openProd
จะเห็นได้ว่า config ของเราถูกแยกกันแล้วต่อไปก็ง่ายต่อการเรียกใช้บน environtment ที่ต่างกันแล้วนะฮะ แล้วพบกันใหม่ :))
Reference
https://docs.cypress.io/api/plugins/configuration-api.html#Usage