how to mock a function inside react component in jest and testing library

Viewed 26

given code of a component with a helper function defined inside the component. how do i return whatever value i want to return with jest and react testing library?

import { act, render } from "@testing-library/react";
import Comp, * as Module from "./helper";

describe("helper", () => {
  // why this one dosen't work?
  test("comp with mock", () => {
    let component;
    const spy = jest.spyOn(Module, "PrintTest"); // dosen't work: .mockResolvedValue("Bob");
    spy.mockReturnValue("bob");

    // console.log(screen.debug());
    act(() => {
      component = render(<Comp />);
    });

    expect(component.getByTestId("original-data")).toBe("Bob");
  });
});

component

export function PrintTest(data) {
  return <div data-testid="original-data">{data}</div>;
}

export default function Comp() {
  return <div>test with: {PrintTest("data from component")}</div>;
}

How do i change the PrintTest to print something else other than "data from component". and maybe "Bob" or whatever?

Thanks!

codesandbox example: https://codesandbox.io/s/holy-bash-qf7pq8?file=/src/helper.js:27-28

0 Answers
Related