"Target container is not a DOM element." Error when testing MockedProvider with cache

I have an editBook mutation which is configured to update the cache object. The object does not have an id field but a ‘ibsn’ field configured with following type policy.

export const cache: InMemoryCache = new InMemoryCache({
  typePolicies: {
    // This tells Apollo Client that Book does not use a conventional id field
    // and to use ibsn instead
    Book: {
      keyFields: ["ibsn"],

When I pass this cache config into MockedProvider it gives an error of

createRoot(...): Target container is not a DOM element.

I can reproduce on sandbox using the simple Dog example and changing id → cd
Development & Testing > Testing React components (forked) - CodeSandbox

I am testing with React Testing library and jest and have tried providing a container with div and id root, wrapping the render components in different ways with a <div id="root"/>

Hey @Ma-ft

This looks like an issue with your setup. Looking at your reproduction, I see that you export getConfiguredCache from index.js. Something to note here is that because you are importing from this file, this file will get executed in your tests. In index.js, you are executing the following:

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

and because this element doesn’t exist in your test environment, the test blows up with the error you’re seeing.

Rather than exporting your cache from index.js, consider moving it to a different file that can be imported both from your tests and your index.js independently. You want to try and ensure the createRoot code in index.js does not get executed as part of your tests.

I’ve updated your reproduction to try this technique and this seems to fix the issue you’re seeing (NOTE: I did not try and ensure all tests pass, but you can see some of the dog.test.js tests pass in this repro).

Hope this helps!


putting the cache in its own file did the trick, thanks!

1 Like