Search code examples
reactjsjestjsdocusaurus

Docusaurus theme/Layout module cannot be found by Jest


I am using Docusaurus to build a documentation site. In one of the react plugin page, I am using import Layout from '@theme/Layout'; from https://docusaurus.io/docs/using-themes

However, the module cannot be picked up by Jest when I write tests for production.

  ● Test suite failed to run

    Cannot find module '@theme/Layout' from 'src/pages/key-fields-filter.js'

    Require stack:
      src/pages/key-fields-filter.js
      src/pages/key-fields-filter.test.js

       98 | import clsx from 'clsx';
       99 | import styles from './key-fields-filter.module.css';
    > 100 | import Layout from '@theme/Layout';
          | ^
      101 | import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

I have setup jest.config.js along with babel.config.js. According to the Docusaurus documentation, the @theme alias to the following path: (Here I am using Layout.js not Navbar.js, but it should be the same.)

website
├── node_modules
│   └── docusaurus-theme
│       └── theme
│           └── Navbar.js
└── src
    └── theme
        └── Navbar.js

So, I set jest.config.js as the following:

moduleDirectories: [
    "node_modules",
    "node_modules/docusaurus-theme/theme",
    "src/theme"
  ],

But it still doesn't work. Anyone knows how Docusaurus works in this case? I tried to manually link the Layout.js from node_modules, but I couldn't find it. I am not even sure how Docusaurus links it in the first place.


Solution

  • I just mock Layout using an empty component since Layout is from docusaurus which doesn't need tests for my project.

    In jest.config.js

    moduleNameMapper: {
        ...,
        '@theme/Layout': '<rootDir>/tests/layout-mock.js'
      },
    

    In layout-mock.js

    import React from 'react';
    export default function Layout(props) {
        return (
            <div>{props.children}</div>
        )
    }