1

Suppose I have a component that calls a function, for example:

// AComponent.js

import { Text, View } from "react-native";
import { getAString } from "./utils/function";

const AComponent = () => {
  return (
    <View>
      <Text>{getAString()}</Text>
    </View>
  );
};

export default AComponent;

and suppose getAString is in another file, and it's as simple as:

// function.js

export function getAString(): string {
  return "This comes from GetAString";
}

I want to test AComponent but with the function mocked:

var AComponent = require("../src/AComponent").default;
import { getAString } from "../src/utils/function";
import { render, screen, fireEvent } from "@testing-library/react-native";

describe("A Component's test", () => {
  it("mocking the function", async () => {
    render(<AComponent />);

    jest.spyOn(AComponent, "getAString").mockImplementation(() => {
      return "This is a mocked result";
    });

    const element = screen.getByText("This is a mocked result");
    expect(element).toBeTruthy();
  });
});


It fails with this message:

Cannot spy on the getAString property because it is not a function; undefined given instead

I guess that it expects that function to be a property of AComponent. But how could I do it then?

4
  • jest.spyOn is looking for a property, andgetAString isn't a property of AComponent. Commented Feb 8, 2023 at 19:13
  • But how could I do it then? Commented Feb 8, 2023 at 19:24
  • In your case I wouldn't bother - you want the component to render "This comes from GetAString", so test that. That leaves you free to confidently refactor how that string is produced. It's only if getAString gets substantially more complex (e.g. that string is on the other end of a network call) that you need a test double. Commented Feb 8, 2023 at 19:29
  • I'll do that, thank you Commented Feb 8, 2023 at 21:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.