react-testing-library icon indicating copy to clipboard operation
react-testing-library copied to clipboard

Support for React.cache function

Open fbjaras opened this issue 5 months ago • 3 comments

Relevant code or config:

// testCached.tsx
import { cache } from 'react';

export default cache((data: number) => {
  return Math.random() * data;
});
----------------------------------------------------------------------
// TestComponent.tsx
import myCachedFunction from "./testCached";
import React from "react";

export const TestComponent = () => {
  return (
    <div>
      <p data-testid="cached-value-component">{myCachedFunction(200)}</p>
    </div>
  );
};
----------------------------------------------------------------------
// TestPage.tsx
import { TestComponent } from "./TestComponent";
import myCachedFunction from "./testCached";
import React from "react";

export function TestPage() {
  return (
    <div>
      <p data-testid="cached-value-page">{myCachedFunction(200)}</p>
      <TestComponent />
    </div>
  );
}
----------------------------------------------------------------------
// Testfile
it("Should use the cached value", () => {
  render(<TestPage />);
  expect(screen.getByTestId("cached-value-page").textContent).toEqual(
    screen.getByTestId("cached-value-component").textContent
  );
});

What you did:

We are using the React.cache function but cannot get it to work in tests.

What happened:

In tests, it does not use the cache but simply returns a new value for each call. When running the above code in nextjs 14 it works as expected and returns the cached value instead of a new value displaying the same value in TestComponent and TestPage.

For example the tests return:

Expected: "158.69893572775896"
Received: "45.853220887195164"

Also worth mentioning i experimented with different solutions, for example some in this issue, but ended up having it mocked.

Reproduction:

Problem description:

Suggested solution:

It should work as expected, or at least mention in docs to mock it

fbjaras avatar Jul 07 '25 08:07 fbjaras