1
votes

I'm reviewing the Alert component from 30 Seconds of Code: React. It works just fine.

I wrote a test but the test fails with the error. Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null https://codesandbox.io/s/goofy-curie-zh2bo

test("renders an alert", () => {
  const { getByTestId } = render(<Alert />);
  expect(getByTestId("alert")).toBeInTheDocument();
});

Any help is appreciated.

2
@ale917k The component renders just fine. Kindly check out the sandbox. The error is received when I run the test. - ln09nv2

2 Answers

1
votes

It might be because you have some ms timeout before component gets rendered.

import { waitForElement } from '@testing-library/react';

test("renders an alert", async () => {
  const { getByTestId } = render(<Alert />);
  await waitForElement(() => getByTestId("alert"));
  expect(getByTestId("alert")).toBeInTheDocument();
});
0
votes

Found this article which solved my issue and passed the test. https://kentcdodds.com/blog/use-ternaries-rather-than-and-and-in-jsx

return (
    <div>
      {isShown ? (
        <div
          className={`alert ${type}${isLeaving ? "leaving" : ""}`}
          role="alert"
          data-testid="alert"
        >
          <button className="close" onClick={closeAlert} />
          {message}
        </div>
      ) : null}
    </div>
  );