所以我正在嘗試測驗表單輸入。首先表單應顯示錯誤,然后在輸入值后用戶單擊按鈕并應洗掉錯誤。
我想我明白為什么會這樣,但我不知道如何測驗這個功能。
我有條件地呈現錯誤訊息并更新狀態,所以我知道這可能是它告訴我將測驗包裝在act(). 我還告訴模擬服務器發送一個錯誤狀態,我想也許是因為我覆寫了初始處理程式,它只會以我定義的錯誤狀態進行回應。那也不行。
我不知道如何準確地測驗這個,因為我是測驗的新手。我真的很感激任何幫助。
下面是測驗函式:
it('clears validation error after username field is updated', async () => {
let validationError;
server.use(generateValidationError('username', 'Username cannot be null'));
setup();
await act(async () => {
userEvent.click(button);
validationError = await screen.findByText('Username cannot be null');
userEvent.type(usernameInput, 'username001');
userEvent.click(button);
expect(validationError).not.toBeInTheDocument();
});
});
uj5u.com熱心網友回復:
由于在組件中設定狀態或異步執行某些操作可能需要“一些時間”,因此您應該將您的情況視為潛在的類似 Promise 的情況。
為了確保您的測驗始終等待發生的任何更改,您可以使用waitFor方法并在代碼中添加回呼函式來檢查某些狀態。這是來自React 測驗庫
it('clears validation error after username field is updated', async () => {
let validationError;
server.use(generateValidationError('username', 'Username cannot be null'));
setup();
await act(async () => {
userEvent.click(button);
userEvent.type(usernameInput, 'username001');
userEvent.click(button);
await waitFor(async () => {
validationError = await screen.findByText('Username cannot be null');
expect(validationError).not.toBeInTheDocument();
});
});
});
提示
當您斷言包含 DOM 元素的內容時,請始終在執行某些操作后選擇該元素(在單擊按鈕后更改驗證狀態)。
在上面的代碼中,我根據上述提示更改了該選擇器的位置。
uj5u.com熱心網友回復:
在方法方面,我會:
- 測驗錯誤最初可見
- 點擊按鈕
- 測驗錯誤已經消失
如果您要使用act(),通常會將斷言放在其函式體之外,請參閱https://reactjs.org/docs/testing-recipes.html#act。
我什至不確定你需要act(). 官方測驗庫檔案中的示例似乎可以滿足您的需求:
- https://testing-library.com/docs/dom-testing-library/api-async#findby-queries
- https://testing-library.com/docs/react-testing-library/example-intro
uj5u.com熱心網友回復:
這真是一個愚蠢的錯誤。我遇到的第一個錯誤是因為我在成功提交后隱藏了我的表單。因此該組件將卸載,然后我將無法對其進行測驗。我通過分別測驗每個欄位并確保它沒有成功提交表單來找到解決方法。
通過修復上述錯誤,我不再需要使用 act() 了,因為我沒有在開玩笑中遇到任何錯誤。之后測驗順利通過。
it.each`
field | message | label
${'username'} | ${'Username cannot be null'} | ${'Username'}
${'email'} | ${'Email cannot be null'} | ${'Email'}
${'password'} | ${'Password cannot be null'} | ${'Password'}
`(
'clears validation error after $field field is updated',
async ({ field, message, label }) => {
server.use(generateValidationError(field, message));
setup();
userEvent.click(button);
const validationError = await screen.findByText(message);
const inputByLabel = screen.getByLabelText(label);
userEvent.type(
inputByLabel,
label === 'Email' ? '[email protected]' : 'username001'
);
//this line was needed to stop the form from submitting
userEvent.type(confirmPasswordInput, 'newpassword');
userEvent.click(button);
await waitFor(() => {
expect(validationError).not.toBeInTheDocument();
});
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362450.html
標籤:javascript 反应 单元测试 玩笑
上一篇:減少回呼函式以從陣列中檢索屬性
下一篇:如何用隨機陣列元素替換文本?
