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: