Library for mocking dependencies in Vitest with TypeScript without need to provide a path.
npm install vitest-auto-mockts
vi.mock('src/components/auth/AuthComponent');
const AuthComponentMock = vi.mocked(AuthComponent);
`
AFTER
`ts
const AuthComponentMock = vi.mocked(AuthComponent);
`
Installation
`sh
npm install -D vitest-auto-mock
`
Requirements
As this library is an extension for vitest, it is required to have vitest already installed.
Configuration
To use automatically provided mocks, the Vite plugin must be used.
`ts
// vite.config.ts
import { defineConfig } from 'vite';
import vitestAutoMockPlugin from 'vitest-auto-mock';
export default defineConfig({
plugins: [vitestAutoMockPlugin()],
{...}
}));
`
The whole feature is automatically activated after enabling the plugin.
If there is a separated configuration for vitest (like vitest.config.ts), it will be a better place to use the plugin.
Usage
`ts
import { App } from 'src/app';
import { render } from '@testing-library/react';
import { RouterProvider } from 'react-router-dom';
// No need to use vi.mock('react-router-dom')
const RouterProviderMock = vi.mocked(RouterProvider);
it('should call RouterProvider', () => {
RouterProviderMock.mockImplementation(() => Router mock);
render( );
expect(RouterProviderMock).toBeCalledTimes(1);
});
`
$3
The primary goal of the library was to make React elements mocking easier. It is checked that vitest-auto-mock is working with @testing-library/react.
$3
The library is providing support for types of vitest mocks. However, it is possible to use it within JavaScript tests.
Limitations
This project is not a magic. It is based on the simple assumption that variable used as an argument of vi.mocked is imported somewhere in the test file. The path is obtained from the AST of the test file, and vi.mock` function with the obtained path is added to the code. Therefore, any non-imported or re-assigned parameter probably will not work.