David
David

Reputation: 7486

How to mock dependency being used in my React component?

I have something akin to the following case:

import { someFunction } from "./utils/function"

class ExampleComponent extends React.Component {

  buildPages = () => {
    return someFunction();
  }

  render() {
    const pages = this.buildPages();

    return <div className="container">{pages}</div>;
  }
}

My code is a lot more complicated than the above, but the above is what it boils down to.

I have the following test:

describe("ExampleComponent", () => {
  it("should match snapshot", () => {
    // Somehow mock someFunction being used in the component.

    expect(mount(getExampleComponent())).toMatchSnapshot();
  };
});

someFunction is an expensive computation, and I basically want it to just be a jest.fn().mockReturnValue(true) when testing. Is there a way to do this? I read up on mocking with jest, but none of them seem to go over this use case. I'm not interested in passing someFunction in as a prop.

Upvotes: 2

Views: 949

Answers (1)

David
David

Reputation: 7486

Turns out it is as simple as this:

import * as Functions from "./utils/function";

describe("ExampleComponent", () => {
  it("should match snapshot", () => {
    jest.spyOn(Functions, "someFunction").mockImplementation(() => {
      return true
    })

    expect(mount(getExampleComponent())).toMatchSnapshot();
  };
});

The import * as Functions from "./utils/function"; is pretty important stylistically, as the jest.spyOn takes two parameters, and you need the function you're spying on as the second parameter string.

Upvotes: 1

Related Questions