-1

I have data

const data = {
  animal: 'cat',
  isBlack: true
}

What I wish my component to render some text if the cat is black and not to render if the cat is not black. I have several tests

describe('About', () => {
  const data = {
      animal: 'cat',
      isBlack: true
  }
  beforeEach(() => {
    fetchMock.getOnce('/api/animals', {data});
  });
  afterEach(() => {
    fetchMock.reset();
    expect(fetchMock.done()).toBe(true);
  });

  it('should render with first text', () => {
    expect(instance.getByText('Black Cats are awesome')).toBeVisible();
  })
  it('should render with second text', () => {
    expect(instance.getByText('Black Cats are my favourite')).toBeVisible();
  })
  it('should render with second text', () => {
    expect(instance.getByText('Black Cats rule')).toBeVisible();
  })
  it('should render no text', () => {
    expect(instance.queryByText('Black Cats rule')).toBeNull();
  })
)

So basically as soon as isBlack is false no text should be rendered. So, what I have now, I have fetchMock in every test, my desire is that I do run fetchMock before each and change the response for the false cases in the tests accordingly. Is there a way?

Katharina Schreiber
  • 1,187
  • 2
  • 11
  • 38

1 Answers1

0

I cannot see yout code but assuming it is more less like this:

  • the component CatComponent
import React from "react";
import { fetchData } from "./fetchCatData";

const CatComponent = () => {
  const [data, setData] = React.useState({});

  React.useEffect(() => {
    const fetchCatData = async () => {
      const data = await fetchData();
      setData(data);
    };

    fetchCatData();
  }, []);

  return (
    <div>
      {data && data.isBlack && (
        <>
          <p>Black Cats are awesome</p>
          <p>Black Cats are my favourite</p>
          <p>Black Cats rule</p>
          <p>Black Cats rule</p>
        </>
      )}
    </div>
  );
};

export default CatComponent;
  • the fetch api: fetchCatData
export const fetchData = async () => {
  return Promise.resolve({ animal: 'dog', isBlack: false })
}

We can have tests like this:

import { render, screen, waitFor } from "@testing-library/react";
import CatComponent from "../CatComponent";

const mockFetchData = jest.fn();
jest.mock("../fetchCatData", () => ({
  fetchData: () => mockFetchData(),
}));

describe("should work tests", () => {
  it("no text", async () => {
    render(<CatComponent />);

    await waitFor(() => {
      expect(
        screen.queryByText("Black Cats are awesome")
      ).not.toBeInTheDocument();
    });
  });

  it('texts present', async () => {
    mockFetchData.mockResolvedValue({ isBlack: true })
    render(<CatComponent />);

    await waitFor(() => {
      expect(
        screen.getByText("Black Cats are awesome")
      ).toBeInTheDocument();
    });

    expect(screen.getByText('Black Cats are my favourite')).toBeInTheDocument();
  })
});
Marek Rozmus
  • 773
  • 7
  • 13