我可以使用 React 測驗庫的fireEvent方法成功實作測驗,但是當我嘗試使用等效測驗時,userEvent我無法讓它觸發任何東西。我怎樣才能解決這個問題?
代碼沙盒
/MyInput.tsx
import { useState } from "react";
export default function MyInput() {
const [inputTextState, setInputTextState] = useState("");
return (
<div>
<label>
My Input
<input
value={inputTextState}
onChange={(event) => setInputTextState(event.target.value)}
/>
</label>
<p>{inputTextState}</p>
</div>
);
}
__tests__/MyInput.test.tsx
import { fireEvent, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MyInput from "../MyInput";
const setup = () => {
const utils = render(<MyInput />);
const input = utils.getByLabelText("My Input") as HTMLInputElement;
return {
input,
...utils
};
};
test("Simply input a number with fireEvent", () => {
const { input } = setup();
fireEvent.change(input, { target: { value: "23" } });
expect(input.value).toBe("23");
});
test("Try userEvent", () => {
const { input } = setup();
userEvent.type(input, "23");
expect(input.value).toBe("23");
});
uj5u.com熱心網友回復:
只是我需要添加異步和等待:
test("Try userEvent", async () => {
const { input } = setup();
await userEvent.type(input, "23");
expect(input.value).toBe("23");
});
@testing-library/user-eventatv13沒有回傳承諾,但更新到了v14。目前,create-react-app提供v13,因此它與最新檔案不匹配。對于初學者來說相當混亂!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475377.html
下一篇:在Dart中遍歷JSON映射
