【问题标题】:Vitest - How to exclude specific files and folders?Vitest - 如何排除特定文件和文件夹?
【发布时间】:2022-12-14 03:57:19
【问题描述】:

我正在将我的项目从 jest 迁移到 vitest,我想排除某些文件和文件夹以进行测试和覆盖,我正在关注 docs 但“exclude”似乎不起作用,每当我运行一些测试时,vitest 都会抛出一个错误来自 config 文件夹,我在那里没有任何测试文件,在 config 文件夹中我有一堆配置文件,包括 setupTests.ts 和 i18n 特定配置,错误来自 i18n.ts 文件。我正在使用 vite 3,下面是我的 vite 配置文件,我还能如何排除文件和文件夹?

环境:

  • Windows 11
  • 节点 16.14.0
  • 维特3.1.0
  • Vitest 0.23.4
  • 列表项

编辑:原来问题出在我模拟 react-i18next 的 setupTests.ts 文件中,当我尝试执行“const actual = await vi.importActual(''react-i18next'' ); return {...actual, ...}" 忽略打字稿的作品。

vi.mock('react-i18next', () => ({
  ...vi.importActual('react-i18next'), // this didn't work
  useTranslation: () => [(key: any) => key],
}));


vi.mock('react-i18next', () => {
  const acutal = vi.importActual('react-i18next'), // this didn't work either
  return {
         ...actual, 
         useTranslation: () => [(key: any) => key],
   };
}); 



  vi.mock('react-i18next', async () => {
  const actual = await vi.importActual('react-i18next'); // this works
  return {
    // @ts-ignore  // have to put this here as typescript was complaining
    ...actual,
    useTranslation: () => [(key: any) => key],
  };
});

vite.config.ts

/// <reference types="vitest" />
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    tsconfigPaths(),
  ],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/config/setupTests.ts',
    css: true,
    mockReset: true,
    restoreMocks: true,
    clearMocks: true,
    include: ['./src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
    exclude: [
      '**/node_modules/**',
      '**/dist/**',
      '**/cypress/**',
      '**/.{idea,git,cache,output,temp}/**',
      './src/config/**',
    ],
    coverage: {
      exclude: ['./src/config'],
    },
  },
}); ```

【问题讨论】:

  • 如果您自己解决了这个问题,您可以将其添加为答案并将其标记为已接受吗?

标签: reactjs react-testing-library vite vitest


【解决方案1】:

我们可以在 test 配置中使用 exclude 属性。

维泰斯特配置可以在vitest.config.ts文件中修改。如果我们想排除共享文件夹包,我们可以将 shared/* 添加到 exclude 部分,如下所示

import { configDefaults } from 'vitest/config'

export default defineConfig({
  plugins: [react(), tsconfigPaths()],
  test: {
    exclude:[
      ...configDefaults.exclude, 
      'shared/*'
    ]
  },
});

这里 configDefaults 包含排除的默认文件夹,如 node_modules,可从 vitest/config 包中使用。如果我们省略 configDefaults.exclude,它也会在 node_modules 文件夹中运行检查。

可以在官方文档中找到更多详细信息here

注意:我已经在 22 年 12 月 14 日进行了测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多