我在一个NextJS项目中使用了绝对导入并测试了一个带有Context Provider的组件。我已根据jest setup设置了此设置
测试:
import { render, screen } from 'test-util';
import { Sidebar } from '@/components/Sidebar/Sidebar';
test('if it has a brand image', () => {
render(<Sidebar />);
const brandLogo = screen.getByAltText('logo');
expect(brandLogo).toBeInTheDocument();
});
字符串
下面是我的test-util.tsx
在根文件夹中。
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 };
型
这是我在根文件夹中的jest.config.js
// @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: './',
});
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
// Handle module aliases (this will be automatically configured for you soon)
'^@/components/(.*)$': '<rootDir>/components/$1',
'^@/pages/(.*)$': '<rootDir>/pages/$1',
'^@/firebase/(.*)$': '<rootDir>/firebase/$1',
'^@/store/(.*)$': '<rootDir>/store/$1',
},
testEnvironment: 'jest-environment-jsdom',
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
型
下面是根文件夹中的jest.setup.js
import '@testing-library/jest-dom/extend-expect';
型
我得到这个错误:
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 |
型
这里是tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/pages/*": ["./pages/*"],
"@/components/*": ["./components/*"],
"@/features/*": ["./features/*"],
"@/firebase/*": ["./firebase/*"],
"@/store/*": ["./store/*"]
}
}
}
型
该如何解决这个问题?我想用
import { render, screen } from 'test-util';
型
适用范围:
import { render, screen } from '../../../test-util';
import { Sidebar } from '@/components/Sidebar/Sidebar';
test('if it has a brand image', () => {
render(<Sidebar />);
const brandLogo = screen.getByAltText('logo');
expect(brandLogo).toBeInTheDocument();
});
型
2条答案
按热度按时间tf7tbtn21#
我有一个类似的配置,但它为我工作。
尝试在
customJestConfig
对象中添加moduleDirectories: ["node_modules", "<rootDir>/"]
。zlwx9yxi2#
我也有类似的问题
字符串
customJestConfig
帮助了我