Search code examples
mockingdependenciesvitevitest

How to mock dependency of dependency with Vitest


I have a test setup with vite and have a dependency of a dependency that needs some mocked options in order to run properly, I currently have it in a __mocks__/nestedDependency.js file. Also in my test/setup.ts file I have a vi.mock('nestedDependency'), however it does not seem to catch it in any way

I previously had the setup with jest and this exact setup worked. Only thing I have migrated from that setup is instead of using jest.requireActual('nestedDependency') I am now using vi.importActual('nestedDependency') for my mocking purposes.


Solution

  • I was facing the same issue and my solution might help you out. I am in a monorepo. The top level package is panel which requires state and common. state also requires common. I need common mocked to be the same even though it's nested through state.

    I realized that when I ran the tests for panel, that state would be accessed via it's bundle, which was using require calls, which vitest will not mock.

    I updated my test config to use alias

    // the source code only uses import
    const unbundledState = resolve(__dirname, '../state/src/index');
    
    export default defineConfig({
      test: {
        environment: 'jsdom',
        setupFiles: ['./tests/test.setup'],
        globalSetup: ['./tests/test.global'],
        alias: {
          '@cai/state': unbundledState,
        },
      },
    });
    
    

    This made vitest run through import statements instead of require statements and thus things were mocked. So my solution works if the nested dependency happens to use import before being bundled.

    This makes me think if it weren't, something like proxyquire could work for you.