iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0

契機

多年以前,第一次使用 Angular 建立專案的模板裡,component 資料夾裡面都會有一個 .spec 的檔案,這是第一次知道 "測試"是可以用程式碼寫的。

又在前輩分享下,認識 Jest 這套工具,了解到寫測試的 紅綠燈概念。

之後很幸運歷經紮實的新人票訓練,接觸到團隊在使用的 Cucumber.jsCypress 工具,才慢慢地知道測試在做什麽。

『 恩, 關鍵字,Jest紅綠燈Cucumber.jsCypress

Cucumber.js

一套支援 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

Cypess

可以做以下種類的測試:

  • End to end
  • Component
  • Integration
  • Unit

Cypress 能在 browser 執行以上的所有測試。

Jest

JavaScript 單元測試框架,Vitest 就是基於 Jest 所開發的測試框架

一個基本測試的架構:

// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

紅綠燈

實作 TDD 的一個開發循環:紅燈 (失敗) -> 綠燈 (成功) -> 重構

https://ithelp.ithome.com.tw/upload/images/20240918/20128122awBhuZ2eKQ.png
圖取自 TDD is not about testing but the design


萌芽

『 關鍵字從 Jest紅綠燈Cucumber.jsCypress 冒出了更多新芽 BDDTDDEnd to end TestComponent TestIntegration TestUnit TestRefactor


參考資源

Cypress Docs - Recipes


上一篇
[Web Game] 基於同樣的需求做比較
下一篇
[測試] 留意 Testing 的出現
系列文
那些經過腦海一瞬的關鍵字們13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言