代码之家  ›  专栏  ›  技术社区  ›  someone

找不到占位符文本为“Search…”reactjs-jest的元素

  •  0
  • someone  · 技术社区  · 3 年前

    我有一个使用 async await

    我正在尝试测试输入的占位符是否呈现。

    然而,我总是会犯以上错误。

    这是组件:

    const [Loading, setLoading] = useState(false)
    const [name, setName] = useState('');
    const [options, setOptions] = useState([])
    const [data, setData] = useState(false)
    
    useEffect(() => {
      setLoading(true)
      const newUsers = async() => {
        const response = await fetch('https://jsonplaceholder.typicode.com/users')
          .then((res) => res.json())
          .then((data) => {
            setData(data)
          });
    
      };
      newUsers();
    }, [])
    
    if (!data) return <p className = 'text-center font-bold text-6xl' > Loading... < /p>
    if (!Loading) return <p className = 'text-center font-bold text-6xl' > Data loaded < /p>
    
    <input id = "input"
    className = 'w-96  h-16 border-1 shadow-lg rounded-lg'
    placeholder = "Search..."
    
    onChange = {
      e => handleChange(e.target.value)
    }
    value = {
      name
    }
    />
       
    

    这是测试

    test('input appears', async () => {
        await waitFor(() => {
            expect(screen.getByPlaceholderText('Search...')).toBeInTheDocument()
          })
    })
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   Yan Brito    3 年前

    看起来你忘记返回输入了

    const [Loading, setLoading] = useState(false)
    const [name, setName] = useState('');
    const [options, setOptions] = useState([])
    const [data, setData] = useState(false)
    
    useEffect(() => {
      setLoading(true)
      const newUsers = async() => {
        const response = await fetch('https://jsonplaceholder.typicode.com/users')
          .then((res) => res.json())
          .then((data) => {
            setData(data)
          });
    
      };
      newUsers();
    }, [])
    
    if (!data) return <p className = 'text-center font-bold text-6xl' > Loading... < /p>
    if (!Loading) return <p className = 'text-center font-bold text-6xl' > Data loaded < /p>
    
    return (    // <---- Return
      <input id = "input"
        className = 'w-96  h-16 border-1 shadow-lg rounded-lg'
        placeholder = "Search..."
    
        onChange = {
         e => handleChange(e.target.value)
        }
        value = {
         name
        }
      />
    );