我有一个吐司组件,分别在单击成功和错误按钮时生成成功和错误toast。
演示-Link
我用jest
和@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() };
}
型
测试失败
● `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 () => {
型
使用for循环单击按钮3次,但接收到的数组中只有一个吐司div。
1条答案
按热度按时间g6ll5ycj1#
我的结论是,当你调用
expect
时,并不是所有的toast都会出现,所以你需要等待它们。尝试使用
waitFor
字符串