med*_*v21 6 typescript reactjs next.js vitest
我正在vitest与一个NextJS13应用程序集成,但在简单的测试运行中遇到了问题。
不确定问题是什么,我尝试进行一些调整,但vitest.config.ts没有成功。我尝试添加该dir选项,修改该include选项以从源文件中获取文件,但没有成功。
我以为可能与文件有关tsconfig.json,但它仍然输出错误。
这是文件的目录
以下是有问题的文件:
vitest.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
setupFiles: 'setupTests.ts',
// dir: './src'
// includeSource: ['src/**/*.{js,ts,tsx}'],
},
});
Run Code Online (Sandbox Code Playgroud)
tsconfig.json
{
"compilerOptions": {
"target": "ES2017",
"lib": ["es6", "dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "ESNEXT",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"incremental": true,
// "paths": {
// "src": ["./src/*"]
// }
},
"exclude": ["node_modules"],
"include": ["vitest.config.ts","**/*.ts", "**/*.tsx", "next-env.d.ts",
"next.config.js"]
}
Run Code Online (Sandbox Code Playgroud)
DataTable.test.tsx - src/common/components/DataTable/DataTable.test.tsx
// components
import DataTable from 'src/common/components/DataTable';
// dependencies
import {describe, it} from 'vitest'
import {screen, render} from '@testing-library/react'
describe('DataTable test', () => {
it('render the app', () => {
// arrange
render(<DataTable />)
// act
const assetText = screen.getByText("asset")
// assert
// expect(assetText).toBeInTheDocument()
})
})
Run Code Online (Sandbox Code Playgroud)
DataTable 组件 - src/common/components/DataTable/DataTable.tsx
export const DataTable = () => {
return (
<div>
<h1>assets</h1>
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
Index.tsx - src/common/components/DataTable/index.tsx
import { DataTable } from 'src/common/components/DataTable/DataTable';
export default DataTable;
Run Code Online (Sandbox Code Playgroud)
我是 vitest 和 nextjs 的新手,非常感谢您的帮助/指导。
要使导入工作正常进行,需要做两件事import DataTable from 'src/common/components/DataTable';:
TypeScript 中的“paths”编译器选项需要/*在“src”键末尾添加一个 ,以便能够解析“src”目录下的路径(请参阅tsconfig.json参考):
{
"compilerOptions": {
"paths": {
"src/*": ["./src/*"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
Vite/Vitest 还需要知道如何解析“src/common/components/DataTable”,这通常通过resolve.alias设置来完成,但您也可以使用插件,例如vite-tsconfig-paths,添加在相关 tsconfig.json 文件中找到的路径别名:
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
export default {
plugins: [tsconfigPaths(), react()],
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5361 次 |
| 最近记录: |