I have a project where it's using Vitest with Jest and React Testing Library. I have made the configuration for unit tests and it's working properly. However when I want to do a jest.mock
on a library/file/React component I get the following error:
ReferenceError: jest is not defined
Here is my configuration:
// setupTests.ts
import matchers from '@testing-library/jest-dom/matchers';
import { expect } from 'vitest';
expect.extend(matchers);
// vitest.config.ts
/// <reference types="vitest" />
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';
import { defineConfig } from 'vitest/config';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), tsconfigPaths()],
test: {
globals: true,
environment: 'jsdom',
include: ['**/*.test.tsx'],
setupFiles: 'setupTests.ts',
},
});
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"src/*": ["./src/*"]
}
},
"include": [
"setupTests.ts",
"vitest.config.ts",
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": ["node_modules"]
}
For mocking, I know you can do vi.mock
but I prefer using jest.mock
since I'm used to doing that setup, is this even possible?
Vitest is not jest. You aren’t using jest. No it’s not possible, but vi.mock and jest.mock do the same thing because the API is similar.
Check the docs for mocking https://vitest.dev/guide/mocking.html#functions