NextJS Client Component Testing error with Jest + Enzyme

42 Views Asked by At

I have a Nextjs app that I am testing with Jest and Enzyme. I get the following error when running yarn test. The test simple checks if the Login component (a client component using the 'use client' directive) has a Tabs component

 Cannot find module 'private-next-rsc-mod-ref-proxy' from 'src/components/login'

Here are the first few lines of the Login component, the error shows a red arrow on the second line (import)

'use client'
import { 
    TextInput,
    PasswordInput, 

Heres the test

import React from 'react'
import Login from '@/components/login';
import {mount, shallow,render} from '../../enzyme'
import { Tabs } from '@mantine/core';

describe('login component', () => {
    test('has Tabs component', () => {
        expect(shallow(<Login />).contains(Tabs)).toBe(true);
    });
});

Heres Enzyme

//enzyme.js in root directory
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

Here's Jest config

import type { Config } from 'jest';
import nextJest from 'next/jest.js'

const createJestConfig = nextJest({
    // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
    dir: './',
    
  })
// Add any custom config to be passed to Jest
const config: Config = {
  // preset: 'ts-jest',
  transform:{
    "^.+\\.[t|j]sx?$": "ts-jest"
  },
  moduleNameMapper: {
      // ...
      '^@/components/(.*)$': '<rootDir>/src/components/$1',
    },
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/enzyme.js'], //Enzyme docs says we dont need this if Jest is v15+
  
  }
export default createJestConfig(config)

Here are the package versions in package.json

"next": "13.4.12",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.7",
"jest": "^29.7.0",
"ts-jest": "^29.1.2"

I read through a couple Stackoverflow solutions:

  • using and removing setupFilesAfterEnv: ['/enzyme.js']
  • my original Enzyme.js file was:
// import Enzyme, { configure, shallow, mount, render } from 'enzyme';
// import Adapter from 'enzyme-adapter-react-16';

// configure({ adapter: new Adapter() });
// export { shallow, mount, render };
// export default Enzyme;
0

There are 0 best solutions below