Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

reactjs - How to test async useEffect?

How to test async useEffect with react-testing-libs ?

i have:

// in other file
const getData = () => {
  return new Promsise(resolve => setTimeout(() => resolve([1, 2, 3]), 5000));
};

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const data = await getData();
      setData(data);
    };
    fetchData();
  }, []);

  return <div>{data.map(item => <span>{item}</span>)}</div>
};

How test this component?

my test now:

it('MyComponent test', async () => {
  await act( async () => {
    render(<MyComponent/>, container);
  });

  expect(container.innerHTML).toMatchSnapshot();
});

But act, render doesn't wait for useEffect().

Why ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

react-testing-library has a clean solution for this. You can wait for the element to appear in the DOM, which means your async useEffect ran its course.

It's called waitFor and it will wait for an assertion to complete before continuing the code. You can use the other utilities like getByText to expect

it('MyComponent test', async () => {
  await act( async () => {
    render(<MyComponent/>, container);
  });

  waitFor(() => {
    // I'd look for a real text here that is renderer when the data loads
    expect(container.queryElement('span')).toBeDefines();
  })

  expect(container.innerHTML).toMatchSnapshot();

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...