【问题标题】:How to test dynamic changes to the DOM via JavaScript with Jest or some other testing library?如何使用 Jest 或其他测试库通过 JavaScript 测试对 DOM 的动态更改?
【发布时间】:2019-03-20 15:42:27
【问题描述】:

我正在根据环境在页面加载时向文档<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 设置的,但我还没有找到一个令人满意的示例来演示如何做到这一点或如何工作。

我是测试新手,如果提供任何解决方案或提示,我将不胜感激。

【问题讨论】:

    标签: javascript unit-testing testing jestjs jsdom


    【解决方案1】:

    我想最简单的测试方法是这样的:

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

    这是因为Jest 的默认test environmentjsdom,它模拟了document

    【讨论】:

      【解决方案2】:
      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');
      });
      

      【讨论】:

      • 添加一些细节将有助于了解为什么这会起作用。
      猜你喜欢
      • 2017-12-07
      • 2021-12-18
      • 2023-02-17
      • 2018-12-01
      • 2020-10-19
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多