測試修正說明 #

問題描述 #

測試執行時出現兩個失敗的測試:

  1. Script elements test: 期望 2 個腳本但實際找到 3 個
  2. GA setup test: 期望找到 1 個 GA 腳本但實際找到 0 個

錯誤訊息 #

1) check build output for a generic post
     sample post
       should have script elements:
   Error: expected { '0': <script async="" src="/js/min.js?hash=8db32dcb3a" defer=""></script>,
'1': <script async="" src="/js/cached.js?hash=29681a444d" defer=""></script>,
'2': <script async="" src="https://www.googletagmanager.com/gtag/js?id=G-4W9182W76K"></script> } to have a length of 2 but got 3

2) check build output for a generic post
     sample post
       should have GA a setup:
   Error: expected 0 to equal 1

根本原因 #

實際生成的 HTML 包含 3 個 <script src> 元素:

  1. /js/min.js?hash=8db32dcb3a - 主要 JS 檔案
  2. /js/cached.js?hash=29681a444d - 快取 JS 檔案
  3. https://www.googletagmanager.com/gtag/js?id=G-4W9182W76K - Google Analytics 腳本

但測試邏輯期望的腳本數量計算錯誤。

修正方案 #

1. 修正腳本元素測試 (test-generic-post.js:66-67) #

修正前:

let has_ga_id = GA_ID ? 1 : 0;
expect(scripts).to.have.length(has_ga_id + 1);

修正後:

let has_ga_id = GA_ID ? 2 : 0;
expect(scripts).to.have.length(has_ga_id + 1);

說明: 當 GA 啟用時,會產生 2 個額外的腳本(cached.js 和 gtag.js),加上基本的 min.js,總共 3 個腳本。

2. 修正 GA 設定測試 (test-generic-post.js:78-83) #

修正前:

expect(scripts[1].getAttribute("src")).to.match(
/^\/js\/cached\.js\?hash=\w+/
);

修正後:

expect(scripts[1].getAttribute("src")).to.match(
/^\/js\/cached\.js\?hash=\w+/
);
expect(scripts[2].getAttribute("src")).to.match(
/^https:\/\/www\.googletagmanager\.com\/gtag\/js\?id=/
);

說明: 新增對第三個腳本的檢查,確認它是 Google Analytics 的 gtag 腳本。

測試結果 #

修正後,測試應該能正確識別:

修正檔案 #

後續修正 #

3. 修正 noscript 元素檢查 (test-generic-post.js:88-90) #

問題: JSDOM 無法正確解析 noscript 元素的 textContent,導致測試找不到 "/api/ga" 內容。

修正前:

if (n.textContent.includes("/api/ga")) {
count++;
expect(n.textContent).to.contain(GA_ID);
}

修正後:

if (n.innerHTML.includes("/api/ga")) {
count++;
expect(n.innerHTML).to.contain(GA_ID);
}

說明: 使用 innerHTML 而不是 textContent 來檢查 noscript 元素內容,因為 JSDOM 對 noscript 元素的 textContent 解析可能有問題。