Jest测试无法使用findAllByRole方法找到role=“alert”的所有元素

ss2ws0br  于 2023-08-01  发布在  Jest
关注(0)|答案(1)|浏览(154)

我有一个吐司组件,分别在单击成功和错误按钮时生成成功和错误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。

g6ll5ycj

g6ll5ycj1#

我的结论是,当你调用expect时,并不是所有的toast都会出现,所以你需要等待它们。
尝试使用waitFor

import { screen, waitFor } from '@testing-library/dom';

...

await waitFor(async () =>
    expect(await screen.findAllByRole("alert")).toHaveLength(3),
  )

字符串

相关问题