如何Mock Webpack打包库内部的依赖?
Let's break down why your initial approach didn't work and how to fix it:
The issue here is that if external-web-components is a pre-bundled library (meaning it already includes vue-directive-tooltip in its compiled code), your top-level jest.mock('vue-directive-tooltip') won't affect the internal reference inside the bundled library—it's not resolving the module from the Node.js module system anymore, it's using a bundled variable instead.
Here are two actionable solutions depending on how external-web-components is packaged:
1. If external-web-components loads vue-directive-tooltip as an external dependency
If the library doesn't bundle vue-directive-tooltip (it declares it as a peer dependency or uses Webpack externals to load it at runtime), you just need to ensure your mock is hoisted before any module imports. Jest automatically hoists jest.mock calls to the top of the file, but make sure you structure your code correctly:
// Mock first—jest hoists this above all imports jest.mock('vue-directive-tooltip', () => ({ // Match the interface the library expects (e.g., an install method for Vue directives) install: jest.fn() })) // Now import your components and the external library import Dep1 from '@/components/Dep1' import Vue from 'vue' const ExternalComponents = require('external-web-components') Vue.use(ExternalComponents) describe('Test dep1', function () { it.only('It should do something', function () { const wrapper = mount(Dep1) // Verify the mock was used (optional) expect(require('vue-directive-tooltip').install).toHaveBeenCalled() }) })
2. If external-web-components bundles vue-directive-tooltip internally
If the library includes vue-directive-tooltip in its compiled code, you'll need to mock the entire external-web-components module instead, replacing its behavior with something that doesn't rely on the real tooltip dependency:
// Mock the entire external library jest.mock('external-web-components', () => ({ install: (Vue) => { // Replicate the parts of the library's install logic that your component Dep1 needs // For example, if the library registers other components or directives, add those here // Skip any code that references vue-directive-tooltip entirely } })) import Dep1 from '@/components/Dep1' import Vue from 'vue' const ExternalComponents = require('external-web-components') Vue.use(ExternalComponents) describe('Test dep1', function () { it.only('It should do something', function () { const wrapper = mount(Dep1) // Add your test assertions here }) })
Quick Troubleshooting Tip
To check if the library bundles its dependencies, inspect the code in node_modules/external-web-components—if you see references to vue-directive-tooltip directly in the compiled main file (not as a require/import), it's bundled, and you'll need the second approach.
内容的提问来源于stack exchange,提问作者feliupe

