admin管理员组

文章数量:1402226

I got a counter (React hooks ponent) which renders a new number incrementally per second. How can I assert a certain number to be in the DOM while it's updated by the hook?

Here's a code sandbox link

import React, { useState, useEffect } from "react";

export default function Counter() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    const intervalId = setInterval(function () {
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(intervalId);
  });

  return <span>{count}</span>;
}

Failing test

  test("should be able to find 3 directly", async () => {
    render(<Counter />);

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });

Passing test

  test("should render one and then two and then three", async () => {
    render(<Counter />);

    const one = await waitFor(() => screen.findByText(/1/i));
    expect(one).toBeInTheDocument();

    const two = await waitFor(() => screen.findByText(/2/i));
    expect(two).toBeInTheDocument();

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });

I got a counter (React hooks ponent) which renders a new number incrementally per second. How can I assert a certain number to be in the DOM while it's updated by the hook?

Here's a code sandbox link

import React, { useState, useEffect } from "react";

export default function Counter() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    const intervalId = setInterval(function () {
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(intervalId);
  });

  return <span>{count}</span>;
}

Failing test

  test("should be able to find 3 directly", async () => {
    render(<Counter />);

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });

Passing test

  test("should render one and then two and then three", async () => {
    render(<Counter />);

    const one = await waitFor(() => screen.findByText(/1/i));
    expect(one).toBeInTheDocument();

    const two = await waitFor(() => screen.findByText(/2/i));
    expect(two).toBeInTheDocument();

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });
Share Improve this question asked Nov 6, 2020 at 16:26 Null HeadNull Head 2,94113 gold badges64 silver badges87 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

According to the documentation, the default timeout is 1000ms, so I think it's timed out before 3 is displayed.

What if you modify the test as follows?

test("should be able to find 3 directly", async () => {
  render(<Counter />);

  const three = await waitFor(() => screen.findByText(/3/i), {
    timeout: 3000
  });
  expect(three).toBeInTheDocument();
});

本文标签: