簡體   English   中英

React 測試庫未更新輸入字段中的 state

[英]React Testing Library not updating state in input field

我是 RLT 的新手,在我嘗試為輸入框編寫單元測試時遇到了這個奇怪的事情,RTL 只是不會更新 state 的輸入值,這是我的測試代碼:

import { fireEvent, screen } from '@testing-library/dom';
import { act, render, waitFor } from '@testing-library/react';
import React from 'react';
import { Component } from './Component';
    
describe('search input', () => {
  it('should update input field', async () => {
     const { getByTestId } = render(
        <Component />
      );
    
    const inputElement = getByTestId('search-text-input');
    expect(inputElement).toBeInTheDocument();
    expect(inputElement).toHaveValue('');
    const country = 'usa';
    await waitFor(() => {
      fireEvent.change(inputElement, { target: { value: country } });
    });

    expect(getByTestId('search-text-input').value).toBe(country);
   });
});

這是我的反應代碼:

import React, { useState } from 'react';

export const Component = () => {
  const [search, setSearch] = useState<string>('');

  const onNameChange = React.useCallback((e) => {
    console.log('onNameChange...', e.target.value);
    setSearch(e.target.value);
  }, []);

  return (
      <input
        data-testid={'search-text-input'}
        autoComplete="off"
        name="search-input"
        onChange={onNameChange}
        size="medium"
        value={search}
        placeholder={'Search'}
      />
  );
};

如您所見,在我的 React 代碼中,當運行測試時,第 7 行已經打印出“usa”,這是我在測試中傳遞的值,但似乎 RTL 只是卡在這里,不會更新 state。

如果有什么幫助,項目本身在 next.js,我擁有的依賴版本是:

"@testing-library/dom": "^8.18.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@types/jest": "^29.0.3",
"@types/node": "18.7.18",
"@types/react": "18.0.21",
"@types/react-dom": "18.0.6",
"react": "18.2.0",
"react-dom": "18.2.0",
"next": "12.3.1",

還在我的另一個本地倉庫中嘗試了這個,react 17.0.2,沒有 next.js,它通過了; 但它不會通過這個反應 18.2.0 和 next.js 回購...

和我的一個朋友核實過,他問我是否兩個 repo 都將測試環境設置為瀏覽器,我檢查了一下,是的,他們都將 testEnv 設置為 jsdom ...

檢查了 jest.config 文件中的一些其他屬性,結果發現錯誤回購中的 jest.config 文件中的 setupFilesAfterEnv 屬性未正確配置,工作回購利用@testing-library/jest-dom/extend-expect ,而錯誤回購正在使用自定義的 js function...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM