I have a toast component that spawns success and error toast on clicking on the success and error buttons respectively.
Demo - Link
I have written a test using jest
and @testing-library/dom
-
import '@testing-library/jest-dom';
import { screen } from '@testing-library/dom';
import { getExampleDom } from '../test-utils';
test.only('\`n\` toasts appear on \`n\` button clicks', async () => {
const { user } = getExampleDom();
const succesBtn = screen.getByRole("button", { name: /Trigger success toast/i });
for(let i = 0; i < 3; i++) {
user.click(succesBtn);
}
const successToasts = await screen.findAllByRole("alert");
expect(successToasts).toHaveLength(3);
});
test-utils.js
import userEvent from '@testing-library/user-event';
import Toast from "./Toast";
import { getEl } from "./utils";
export function getExampleDom() {
document.body.innerHTML = `
<div id="controller">
<button id="successBtn">Trigger Success Toast</button>
<button id="errorBtn">Trigger Error Toast</button>
</div>
`;
/**
* Test behaves unexpectedly after requiring index file
* -> First test passes
* -> Subsequent test fails
* -> TODO: need to mock style, comment style import from index.js meanwhile.
*/
//require("./index");
/** require("../index"); not working correctly, writing js logic manually below*/
const toast = new Toast({ closable: true });
getEl('#successBtn').addEventListener('click', function handleSuccessBtnClick(e) {
toast.success('Spawned a success toast');
});
getEl('#errorBtn').addEventListener('click', function handleErrorBtnClick(e) {
toast.error('Spawned an error toast');
});
return { user: userEvent.setup() };
}
test fails
● `n` toasts appear on `n` button clicks
expect(received).toHaveLength(expected)
Expected length: 3
Received length: 1
Received array: [<div aria-label="Spawned a success toast" class="toast toast__success" data-id="0" role="alert">Spawned a success toast<span class="toast-dismiss" data-close-id="0">x</span></div>]
24 |
25 | const successToasts = await screen.findAllByRole("alert");
> 26 | expect(successToasts).toHaveLength(3);
| ^
27 | });
28 |
29 | test('Display error toast on `Trigger Error Toast` button click', async () => {
Button is clicked 3 times using for loop, but received array has only one toast div in it.