iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 26
0
Modern Web

遺留系統重構 - 從 MEAN Stack 轉移到 go-vue-postgresql系列 第 26

Day 26 : Jest - 前端測試

當專案越來越大,開發越來越複雜時,測試就是一項保險機制。

在 Gamilms 的前端測試用的框架,這裡選用 Jest

新建專案時選擇單元測試
新建專案時選擇單元測試

選擇 jest
選擇 jest

分隔各組件設定
分隔各組件設定

對於前端工程師來說,確保資料與頁面的連接,是經常需要處理的事務,
過程中的邏輯,就是最需要被測試的部分,
將這些邏輯獨立出來,以利測試與引用,
src 下建立 domains 來存放,
arch

因為有分隔組件設定,為了只測試 domains 下的邏輯,
需要調整根目錄下的 jest.config.js
moduleNameMapper 調整成 domains 的路徑。

// jest.config.js
module.exports = {
  moduleFileExtensions: ["js", "jsx", "json", "vue"],
  transform: {
    "^.+\\.vue$": "vue-jest",
    ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$":
      "jest-transform-stub",
    "^.+\\.jsx?$": "babel-jest"
  },
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/domains/$1"
  },
  snapshotSerializers: ["jest-serializer-vue"],
  testMatch: [
    "**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
  ],
  testURL: "http://localhost/"
};

建立一個簡單的範例

// sum.js
function sum(a, b) {
    return a + b;
}

module.exports = sum;

\tests\unit 資料夾中建立測試檔案

// sum.spec.js
import sum from "@/sum.js";

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

在專案目錄執行測試
在專案目錄執行測試

於是完成了一個簡單的 Jest 單元測試。


上一篇
Day 25 : 續 gRPC : 雙向串流
下一篇
Day 27 : 測試 - 在 Golang 寫測試
系列文
遺留系統重構 - 從 MEAN Stack 轉移到 go-vue-postgresql30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言