I have a small app created in Vanilla JavaScript. To test the app, I am using Jest and JSDOM. I have a button in the app which deletes a table in row. The test looks like:
it('Table deletes corresponding row when Delete is clicked', () => {
const tableCells = document.querySelectorAll('table tbody tr td');
expect(tableCells[1].innerHTML).toBe('Some value');
const firstRowDeleteButton = document.querySelectorAll('table tbody tr button')[1];
firstRowDeleteButton.click();
expect(tableCells[1].innerHTML).toBe('Another value'); // row value should change after original row is deleted.
});
Above test fails as Jest receives the same 'Some value' after at the end of test too. So the delete button is not clicking (be assured that delete functionality is working fine as I tested it in the actual app). I even tried simulating click event like this:
const evt = document.createEvent("HTMLEvents");
evt.initEvent("input", false, true);
element.dispatchEvent(evt);
But this didn't work either. So how can I trigger the click event in JSDOM?
Yes, that is a JSDOM limitations, you should use something like https://testing-library.com/docs/ecosystem-user-event
...
userEvent.click(firstRowDeleteButton)
...
NOTE: examples on this page includes React but user-event works fine apart