Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide
TEST:
import { render, screen } from 'test-util';
import { Sidebar } from '@/components/Sidebar/Sidebar';
test('Ensuring the presence of a brand image', () => {
render(<Sidebar />);
const brandLogo = screen.getByAltText('logo');
expect(brandLogo).toBeInTheDocument();
});
Below is my test-util.tsx
located in the root folder.
import React, { FC, ReactElement, ReactNode } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { AuthProvider } from 'store/auth';
const AllTheProviders: FC = ({ children }) => {
return <AuthProvider>{children}</AuthProvider>;
};
const customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'wrapper'>) =>
render(ui, { wrapper: AllTheProviders, ...options });
export * from '@testing-library/react';
export { customRender as render };
This is my jest.config.js
located in the root directory.
// @ts-nocheck
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Additional configuration to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'^@/components/(.*)$': '<rootDir>/components/$1',
'^@/pages/(.*)$': '<rootDir>/pages/$1',
'^@/firebase/(.*)$': '<rootDir>/firebase/$1',
'^@/store/(.*)$': '<rootDir>/store/$1',
},
testEnvironment: 'jest-environment-jsdom',
};
// Exported this way to enable next/jest loading the Next.js config which is asynchronous
module.exports = createJestConfig(customJestConfig);
This is jest.setup.js
within the root folder.
import '@testing-library/jest-dom/extend-expect';
The encountered error:
FAIL components/Sidebar/__test__/Sidebar.test.tsx
● Test suite failed to run
Cannot find module 'test-util' from 'components/Sidebar/__test__/Sidebar.test.tsx'
1 | import { Sidebar } from '@/components/Sidebar/Sidebar';
> 2 | import { render } from 'test-util';
| ^
3 |
Here is tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/pages/*": ["./pages/*"],
"@/components/*": ["./components/*"],
"@/features/*": ["./features/*"],
"@/firebase/*": ["./firebase/*"],
"@/store/*": ["./store/*"]
}
}
}
To overcome this issue, I aim to use
import { render, screen } from 'test-util';
A valid alternative approach that works for me is:
import { render, screen } from '../../../test-util';
import { Sidebar } from '@/components/Sidebar/Sidebar';
test('Ensuring the presence of a brand image', () => {
render(<Sidebar />);
const brandLogo = screen.getByAltText('logo');
expect(brandLogo).toBeInTheDocument();
});