简体   繁体   中英

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). 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)?

  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.

  3. Is there a click event on the button( check the browser inspector events tab )?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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