測試執行時出現兩個失敗的測試:
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>
元素:
/js/min.js?hash=8db32dcb3a
- 主要 JS 檔案/js/cached.js?hash=29681a444d
- 快取 JS 檔案https://www.googletagmanager.com/gtag/js?id=G-4W9182W76K
- Google Analytics 腳本但測試邏輯期望的腳本數量計算錯誤。
修正前:
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 個腳本。
修正前:
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 腳本。
修正後,測試應該能正確識別:
scripts[0]
: 主要 JavaScript 檔案 (/js/min.js
)scripts[1]
: 快取 JavaScript 檔案 (/js/cached.js
)scripts[2]
: Google Analytics 腳本 (https://www.googletagmanager.com/gtag/js
)test/test-generic-post.js
(第 66, 67, 81-83, 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 解析可能有問題。