Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Support for React.cache function #1407

Open
@fbjaras

Description

  • @testing-library/react version: 16.3.0
  • Testing Framework and version: Tested in vitest@3.2.4 and jest@29.7.0
  • DOM Environment: jsdom@26.1.0
  • Node 20 or 22

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /