【问题标题】:Testing jQuery Animations with Jest用 Jest 测试 jQuery 动画
【发布时间】:2018-12-11 21:52:58
【问题描述】:

我想测试 jQuery 动画状态,而无需等待它们完成使用 Jest 测试框架。我尝试使用jest.useFakeTimers 和所有相关的计时器方法,但没有成功。

$(() => {
  const $button = $('button');
  const $ul = $('ul');
  
  $button.click(() => {
    $ul.slideToggle();
  });
  
  // Random Test - Not Jest
  $button.click();
  console.log("Visible", $ul.is(':visible') === true);
  $button.click();
  console.log("Hidden", $ul.is(':visible') === false);
});
ul { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Toggle</button>
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

【问题讨论】:

    标签: javascript jquery unit-testing jquery-animate jestjs


    【解决方案1】:

    jQuery 提供了一个fx.off 设置,它将强制动画自动跳转到它们的最终状态。

    beforeAll(() => {
      $.fx.off = true;
    });
    
    afterAll(() => {
      $.fx.off = false;
    });
    
    test('whatever you want', () => {
     // ....
    })
    

    文档在这里:https://api.jquery.com/jquery.fx.off/

    【讨论】:

      【解决方案2】:

      您可以模拟/挂钩jQuery.speed,以便所有动画都是即时的。

      $(() => {
        const $button = $('button');
        const $ul = $('ul');
        
        $button.click(() => {
          $ul.slideToggle();
        });
      
        // Hook/Mock jQuery.speed
        const OGSpeed = jQuery.speed;
        jQuery.speed = function(_speed, easing, callback) {
          return OGSpeed(0, easing, callback);
        };
      
        // Random Test - Not Jest
        $button.click();
        console.log("Visible", $ul.is(':visible') === true);
        $button.click();
        console.log("Hidden", $ul.is(':visible') === false);
      });
      ul { display: none; }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      
      <button>Toggle</button>
      <ul>
        <li>A</li>
        <li>B</li>
        <li>C</li>
      </ul>

      【讨论】:

        猜你喜欢
        • 2021-02-03
        • 2020-05-26
        • 2011-08-06
        • 1970-01-01
        • 1970-01-01
        • 2018-07-26
        • 2020-11-24
        • 2018-06-10
        • 2020-11-06
        相关资源
        最近更新 更多