1

I have one component thats use a advanced hook, the advanced hook has been tested and its ok, but I don't know how test the component thats use this hook, with mocking data.

The hook test:

import { renderHook, act } from "@testing-library/react-hooks";
import {
  HookProvider,
  useHook
} from "hooks/useHook";
import { render } from "tests/test-utils";

export const wrapper = ({ children }) => (
  <HookProvider>
    {children}
  </HookProvider>
);

describe("Should advanced hook works", () => {
  it("Should hook has initial states", () => {
    const { result } = renderHook(() => useHook());
    expect(result.current.selectedProducts).toStrictEqual([]);
  });

  it("Test change states", async () => {
    const { result } = renderHook(() => useHook(), {
      wrapper
    });

    act(() => {
      result.current.setSelectedProducts([{_id: ""a14da5", title: "product test", description: "description of product test"}]);
    });

    expect(result.current.selectedProducts[0]._id).toBe("a14da5");
  });
});

The component test:

import { renderHook, act } from "@testing-library/react-hooks";

import {
  HookProvider,
  useHook
} from "hooks/useHook";
import { render } from "tests/test-utils";
import SelectedProductCard from ".";
import { screen, waitFor } from "@testing-library/react";

export const wrapper = ({ children }) => (
  <HookProvider>
    {children}
  </HookProvider>
);

it("Renders correctly SelectedProductCard", async () => {
  const { result } = renderHook(() => useHook(), {
    wrapper
  });

  act(() => {
    result.current.setSelectedProducts([{_id: ""a14da5", title: "product test", description: "description of product test"}]);
  });

   render(
        <SelectedProductCard
          key={a14da5}
          selectedProduct={{_id: ""a14da5", title: "product test", description: "description of product test"}}
        />
  );

  expect(
    screen.getAllByTestId("div-selected-product-card-container")
  ).toMatchSnapshot();
});

but the test of components not works. How can I test this component mocking data?

  • What do you mean by " not works". Is there any error? What's the test result? Show the code of the component. – Lin Du Jun 28 '22 at 02:50

0 Answers0