相关疑难解决方法(0)

React 测试库不更新状态

我的组件:

import React from 'react'

const TestAsync = () => {
  const [counter, setCounter] = React.useState(0)

  const delayCount = () => (
    setTimeout(() => {
      setCounter(counter + 1)
    }, 500)
  )
  
return (
  <>
    <h1 data-testid="counter">{ counter }</h1>
    <button data-testid="button-up" onClick={delayCount}> Up</button>
    <button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
 </>
    )
  }
  
  export default TestAsync
Run Code Online (Sandbox Code Playgroud)

我的测试文件:

describe("Test async", () => {
  it("increments counter after 0.5s", async () => {
    const { getByTestId, getByText } = render(<TestAsync />);

    fireEvent.click(getByTestId("button-up"));

    const counter …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs react-testing-library react-hooks

4
推荐指数
1
解决办法
2万
查看次数