最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JEST | Assert a function was called inside addEventListener callback - Stack Overflow

programmeradmin5浏览0评论

I have the following function:

Code to test

export default function main() {
    const createAndAppendPTag = () => {
        const p = document.createElement('p');
        document.body.appendChild(p);
    };

    window.document.addEventListener('click', () => {
        createAndAppendPTag();
    });
}

The question is: How can I assert using Jest that createAndAppendPTag was called upon a document click event ?



Jest

This is what I tried, but can't seem to make the test pass:

import main from './main'

window.document.addEventListener = jest.fn();
const createAndAppendPTag = jest.fn();

describe('Main', () => {
    const documentClickEvent = new Event('click');

    test('appends p tag to the document', () => {
        // dispatching event before and after invoking `main` to be sure
        window.document.dispatchEvent(documentClickEvent);

        main();

        window.document.dispatchEvent(documentClickEvent);

        expect(window.document.addEventListener).toHaveBeenNthCalledWith(1, 'click', () => {});
        expect(createAndAppendPTag).toHaveBeenCalledTimes(1);
    });
});

Terminal

This results in the following:

发布评论

评论列表(0)

  1. 暂无评论