unit test with react, testing library and jest
# javascript
y
unit test with react, testing library and jest
I'm new to React and Jest and trying to create a simple unit test for a component that loads data via Supabase. I faced a couple of issues that seems to disappear. Would like to know if this is the right way to test.
my component is pretty straightforward where it simply loads data from supabase.
Copy code
export default function FeaturedAreas() {
  const [loading, setLoading] = useState(true);
  const [featuredAreas, setFeaturedAreas] = useState(null);

  useEffect(() => {
    getFeaturedAreas();

    return () => setFeaturedAreas([]);
  }, []);

  async function getFeaturedAreas() {
    try {
      setLoading(true);

      let { data, error, status } = await supabase
        .from('towns')
        .select('name, slug, image_tablet')
        .eq('is_featured', true);

      if (error && status !== 406) {
        throw error;
      }

      if (data) {
        setFeaturedAreas(data.slice(0, 4)); // get first 4 results only
      }
    } catch (error) {
      alert(error.message);
    } finally {
      setLoading(false);
    }
  }

  if (loading) return <p>Loading data...</p>;
  if (featuredAreas?.length < 1) return <p>No areas found</p>;

  return (
    <>...</>
  )
}
this is my test:
Copy code
import FeaturedAreas from '@components/FeaturedAreas';
import { render, screen, waitFor } from '@testing-library/react';

describe('FeaturedAreas', () => {
  beforeEach(() => {
    render(<FeaturedAreas />);
  });

  it('renders loading state', () => {
    expect(screen.getByText(/loading data.../i)).toBeInTheDocument();
  });

  it('renders featured areas', async () => {
    await waitFor(() => {
      expect(screen.getByText(/Bedok/i)).toBeInTheDocument();
    });
  });
});
while the test passed, I'm seeing 2 warnings/errors which I can't seem to figure out.
do I need to mock the supabase client and return value?
probably mock the api