如何在react中使用Jest进行异步按钮点击



我正在为React应用程序编写测试用例。有一个登录按钮必须在提交时启动。但我知道我该如何进行异步调用,并检查它是否成功。这个登录函数内部有一个promise函数。我还需要检查本地存储中的令牌数据。感谢您的帮助。

it("renders LoginComp correctly", () => {
const { getByTestId } = render(<LoginComponent></LoginComponent>)
const input_user = getByTestId('lg_username');
input_user.value = 'admin';
const input_pass = getByTestId('lg_password');
input_pass.value = 'admin';
const j = getByTestId('lg_btn').click();
console.log(localStorage.getItem('tokenized'))
})

有帮助程序等待特定的结果。您应该使您的测试函数异步,以便能够使用它。如果是你的话,我会选择这样的东西。

it("renders LoginComp correctly", async () => {
...
await waitFor(() =>  expect( /* assert on the result or side effect of the async call */)
});

https://testing-library.com/docs/dom-testing-library/api-async

最新更新