多年以前,第一次使用 Angular 建立專案的模板裡,component 資料夾裡面都會有一個 .spec 的檔案,這是第一次知道 "測試"是可以用程式碼寫的。
又在前輩分享下,認識 Jest 這套工具,了解到寫測試的 紅綠燈概念。
之後很幸運歷經紮實的新人票訓練,接觸到團隊在使用的 Cucumber.js 和 Cypress 工具,才慢慢地知道測試在做什麽。
『 恩, 關鍵字,Jest、紅綠燈、Cucumber.js、Cypress 』
一套支援 BDD (Behaviour-Driven Development) 的工具。BDD 是一種軟體開發方式,希望業務端和技術端能一起協作,並拉近各個角色之間的距離,特色是以簡單的口語方式撰寫要做的測試,讓每個角色都能參與測試案例的撰寫,而不只有工程師參與測試。
// 寫法 1
Feature: Addition
  Scenario: Sum of two numbers
  
    Given first number is 10 and second number is 20
    When user executes sum function
    Then the sum is 30
// 寫法 2
Feature: Addition
  Scenario: Sum of two numbers
    Given first number is 10
    And second number is 20
    When user executes sum function
    Then the sum is 30
// 寫法 3
Feature: Addition
  Scenario: Sum of two numbers
  
    Given user wants to sum the following numbers:
      | 10 |
      | 20 |
    When user executes sum function
    Then the sum is 30
    
// 寫法 4
Feature: Addition
  Scenario Outline: Sum of two numbers
    Given first number is <firstNumber>
    And second number is <secondNumber>
    When user executes sum function
    Then the sum is <result>
    Examples:
      | firstNumber | secondNumber | result |
      | 10          | 20           | 30     |
      | 50          | 60           | 110    |
範例取自 Examples to show different ways of creating cucumber feature files
可以做以下種類的測試:
End to end
Component
Integration
Unit
Cypress 能在 browser 執行以上的所有測試。
JavaScript 單元測試框架,Vitest 就是基於 Jest 所開發的測試框架
一個基本測試的架構:
// sum.test.js
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
實作 TDD 的一個開發循環:紅燈 (失敗) -> 綠燈 (成功) -> 重構

圖取自 TDD is not about testing but the design
『 關鍵字從 Jest、紅綠燈、Cucumber.js、Cypress 冒出了更多新芽 BDD、TDD、End to end Test、Component Test、Integration Test、Unit Test、Refactor 』