簡體   English   中英

如何使用 Jest 或其他測試庫通過 JavaScript 測試對 DOM 的動態更改?

[英]How to test dynamic changes to the DOM via JavaScript with Jest or some other testing library?

我根據環境在頁面加載時向文檔<head>動態添加<script>標記。

功能:

export const loadScript = () => {
  // load script tag into head
  const HEAD = document.getElementsByTagName('head')
  const SCRIPT_TAG = document.createElement('script')
  SCRIPT_TAG.setAttribute('src', process.env.SCRIPT_SRC)
  SCRIPT_TAG.setAttribute('async', true)
  HEAD[0].append(SCRIPT_TAG)
}

我想編寫一個測試來檢查loadScript()函數是否在運行后<script>標記進入頭部。 我們的環境是用 Jest 設置的,我還沒有找到一個令人滿意的示例來演示如何做到這一點或如何工作。

我是測試新手,希望能提供任何解決方案或提示。

我想最簡單的測試方法是這樣的:

test('loadScript', () => {
  process.env.SCRIPT_SRC = 'the-src';
  loadScript();
  expect(document.head.innerHTML).toBe('<script src="the-src" async="true"></script>');
});

這是有效的,因為Jest的默認測試環境是模擬document jsdom

test('loadScript', () => {
  loadScript();
  const script = document.getElementsByTagName('script')[0];
  // trigger the callback
  script.onreadystatechange(); // or script.onLoad();
  expect("something which you have on load").toBe('expected result on load');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM