I’m working on a react app and was about to write tests in vitest where i need to mock some react components. For this i wanted to create a __mocks__
directory where the mocked components live however for instance with
vi.mock('@/Components/Description')
vitest won’t use the mock that is in src/Components/__mocks__/Descritpion.tsx
.
my project structure looks like this
├── __mocks__
│ ├── some_node_module.ts
├── node_modules
├── src
│ ├── App.tsx
│ ├── main.ts
│ ├── Components
│ │ │ ├── __mocks__
│ │ │ │ ├── Description.tsx
│ │ │ ├── Description
│ │ │ │ ├── Description.tsx
│ │ │ │ ├── Description.module.sass
│ │ │ │ ├── index.ts //exports the component
│ │ │ ├── Page
│ │ │ │ ├── index.ts
│ │ │ │ ├── Page.tsx
│ │ │ │ ├── Page.test.tsx //want to mock Description in here
│ │ │ │ ├── Page.module.sass
├── package.json
├── package-lock.json
and i’m using it with the following vite.config.ts
// not showing imports
const config = defineConfig({
optimizeDeps: {
include: ['**/*.sass'],
},
plugins: [react(), svgLoader()],
css: {
postcss: {
plugins: [autoprefixer()],
},
modules: {
localsConvention: 'camelCaseOnly',
},
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
});
const testConfig = defineTestConfig({
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/tests/setup.ts',
include: ['**/*.test.{js,ts,jsx,tsx}'],
includeSource: ['src/**/*/.{ts,tsx}'],
exclude: [...defaultExclude, '**/*/index.{js,ts,jsx,tsx}'],
resolveSnapshotPath: (testPath, snapExtension) => testPath.replace('src', '.snapshots') + snapExtension,
},
});
export default mergeConfig(config, testConfig);
according to the docs when mocking a file vitest will look into any __mocks__
folder adjacent to a given file but apparently this doesn’t work with this folder structure and by importing with path/to/component_directory
.
I tried to add the mocks folder to the given components directories but vitest still won’t pick up the manual mock.
Where did i went wrong to properly manually mock my modules?