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?
jest.spyOnis looking for a property, andgetAStringisn't a property ofAComponent."This comes from GetAString", so test that. That leaves you free to confidently refactor how that string is produced. It's only ifgetAStringgets substantially more complex (e.g. that string is on the other end of a network call) that you need a test double.