简体   繁体   English

如何使用非反应代码模拟 Jest 中的按钮点击

[英]How to simulate button click in Jest with Non-React Code

I have some snippets of Vanilla Javascript Code (with JQuery but no major front-end frameworks like React/Angular).我有一些 Vanilla Javascript 代码片段(使用 JQuery,但没有像 React/Angular 这样的主要前端框架)。 The code looks like this代码看起来像这样

setupIconClickEvents() {
    $('#someButton').on('click', (e) => {
        callFunction(parameters);
        e.stopPropagation();
    });
}

I want to simulate the button click to test that the function was called, which I can do easily with a spy.我想模拟按钮单击以测试该函数是否被调用,我可以通过间谍轻松完成。 However the function never gets hit inside.然而,该函数永远不会被击中。 This is my current attempt这是我目前的尝试

describe('setupIconClickEvents()', () => {
    beforeAll(() => {
        object.setupIconClickEvents();
        document.body.innerHTML = `
            <div>
                <button id="someButton"></div>
            </div>
        `;
    });

    describe('rankIcon', () => {
        it('should stop event propagation', () => {
            jest.spyOn(object, 'callFunction');
            $('#someButton').trigger('click');
            expect(object.callFunction).toHaveBeenCalled();
        });
    });
});

How can I get inside the snippet of code when I click my button?单击按钮时如何进入代码片段?

  1. Are you sure that the code block where the trigger call is placed gets executed at all(trace it adding console.log('hit') ; before the trigger line)?您确定放置触发器调用的代码块完全被执行(跟踪它添加console.log('hit') ; 在触发行之前)?

  2. Does the selector work(dump its result- console.log($('#someButton')); ?- given that you generate the html dynamically it is a common mistake to mix the order of operations and try to select element that is not on the page.选择器是否工作(转储其结果 - console.log($('#someButton')); ?- 考虑到您动态生成 html,混合操作顺序并尝试选择不是的元素是常见错误在页面上。

  3. Is there a click event on the button( check the browser inspector events tab )?按钮上是否有点击事件(检查浏览器检查器事件选项卡)?

我看到了另一个答案,你可以测试函数本身,来自 html 的一部分,在 selenium e2e 测试中,你进行这种测试不是模拟点击,而是让 selenium 驱动器真正点击按钮。

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

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