I have a component named MyComponent and it calls 2 APIs when it mounts. 1st API shows the initial data and when I click a particular button, it shows data from 2nd API. I have used useRef to decide which data to show.
const MyComponent = () => {
const random = React.useRef(false);
const { data, isFetching, isError } = useMakeFirstAPICall();
const { data: a, isFetching: b, isError: c, refetch: d } = useMakeSecondAPICall();
const usedData = random.current ? a : data;
const usedIsFetching = random.current ? b : isFetching;
const usedIsError = random.current ? c : isError;
return (
<View>
<Pressable
testID="my.btn"
onPress={() => {
random.current = true;
d();
}}
>
<MyCustomIcon />
</Pressable>
{!usedIsFetching && <ShowData data={usedData} />}
</View>
);
}
I was testing the data changes after the button click. I have managed to mock api calls. But after button click the data is not changing. I tried to mock the useRef value but it's not working. What am I doing wrong here?
This is my test code.
jest.mock("src/api1", () => ({
useMakeFirstAPICall: () => ({
data: MockData1,
}),
}));
jest.mock("src/api2", () => ({
useMakeSecondAPICall: () => ({
data: MockData2,
}),
}));
describe("Testing MyComponent", () => {
test("Test button press action", async () => {
const reference = { current: true };
Object.defineProperty(reference, "current", {
get: jest.fn(() => null),
set: jest.fn(() => null),
});
jest.spyOn(React, "useRef").mockReturnValueOnce(reference);
render(<MyComponent />);
const gridList1 = await screen.findAllByTestId("grid.card");
expect(gridList1).toBeTruthy();
expect(gridList1.length).toBe(5);
const myButton = await screen.findByTestId("my.btn");
await fireEvent(myButton, "click");
const gridList2 = await waitFor(() => screen.findAllByTestId("grid.card"));
expect(gridList2).toBeTruthy();
expect(gridList2.length).toBe(2);
});
});
This is the error it's giving me.