简体   繁体   English

如何在此 Jest 测试中触发 window 加载事件?

[英]How do I trigger the window load event in this Jest test?

I'm trying to set up my first DOM-manipulation/JQuery Jest test in my Rails project.我正在尝试在我的 Rails 项目中设置我的第一个 DOM 操作/JQuery Jest 测试。 In its essential form at the moment, I'm just trying to clear a basic hurdle of 'imported Javascript functions do anything at all'.目前,在其基本形式中,我只是想清除“导入的 Javascript 函数可以做任何事情”的基本障碍。

To that end, I have the following code in PledgeFormUpdates.js.test:为此,我在 PledgeFormUpdates.js.test 中有以下代码:

'use strict';

import pledge_form_updates from '../../app/javascript/components/PledgeFormUpdates.js';

test('Displays GDPR checkbox on EU country selection', () => {

  // Set up our document body
  document.body.innerHTML =
    '<select id="pledge_pledgor_home_country" class="country-select"></select>'// +

    pledge_form_updates();
    const $ = require('jquery');

    $(window).trigger('load');
    $("#pledge_pledgor_home_country").trigger('change');
});

And in PledgeFormUpdates.js I have the following:在 PledgeFormUpdates.js 我有以下内容:

export default function() {
  console.log('hello world');
  window.addEventListener("load", function() {

    console.log('mellow curled');
    $("#pledge_pledgor_home_country").change(function() {
      console.log('yellow twirled')
    });
  });
};

So when I run the test, I'm expecting to see printout including 'hello world', 'mellow curled' and 'yellow twirled'.因此,当我运行测试时,我希望看到打印输出包括“hello world”、“mellow curled”和“yellow twirled”。 But in practice it's stopping after the first output, and so presumably the window load event isn't actually getting triggered (which I confirmed by commenting out the window.addEventListener... line, then seeing all three printouts).但实际上它在第一个 output 之后停止,因此可能 window load事件实际上并没有被触发(我通过注释掉window.addEventListener... .

What am I doing wrong here - or rather, how should I trigger the load event?我在这里做错了什么 - 或者更确切地说,我应该如何触发加载事件? (I also tried $(window).load(); , but that just raises a TypeError) (我也试过$(window).load(); ,但这只会引发 TypeError)

I found a workaround for this, though it seems quite hacky.我找到了一个解决方法,虽然它看起来很hacky。 In the tested file, if I substitute the line在测试文件中,如果我替换该行

window.addEventListener("load", function() { , window.addEventListener("load", function() { ,

with

$(window).on("load", function() {

then running the test (including the $(window).trigger('load'); statement) prints all of the log lines.然后运行测试(包括$(window).trigger('load');语句)打印所有日志行。

I must be missing something, because I can't believe that Jest would require JQuery to trigger a page load event, but for now at least this works.我一定遗漏了一些东西,因为我不敢相信 Jest需要JQuery 来触发页面加载事件,但至少现在这可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM