模拟 webpack“外部"的正确方法(即 jquery)在 Vue 单元测试中(使用 mocha) [英] Correct way to mock webpack "externals" (i.e. jquery) in Vue unit tests (using mocha)
问题描述
我有一个使用 Vue CLI v3.5 创建的 Vue 项目,我正在尝试编写一些组件单元测试.我在 vue.config.js 中有 jquery 作为 webpack 外部,如下所示:
I have a Vue project which was created using Vue CLI v3.5 and am trying to write some component unit tests. I have jquery as a webpack external in vue.config.js as follows:
...
configureWebpack: {
externals: {
jquery: 'jQuery'
}
}
...
然后我在 index.html 的脚本标签中从 CDN 加载 jquery.显然,每当我运行 vue-cli-service test:unit
时,我都会收到以下错误,因为 jquery 不是项目中的依赖项:
and I load jquery from a CDN in a script tag in index.html. Obviously whenever I run vue-cli-service test:unit
I get the following error since jquery isn't a dependency in the project:
RUNTIME EXCEPTION Exception occurred while loading your tests
ReferenceError: jQuery is not defined
at Object.jquery (.../public/webpack:/external "jQuery":1:1)
...
我意识到在我的单元测试中我可能应该在某处模拟 jquery,但我不确定这样做的正确方法是什么,所以我只在测试配置中的一个地方进行.
I realize in my unit tests I should probably mock jquery somewhere, but I'm not sure what's the correct way to do this so I only do it in one place within the testing config.
推荐答案
使用 Vue.js(我看到你已经标记了你的问题),我创建了自己的 vue.config.js
如下图.
Using Vue.js (as I see you've tagged your question thus), I created my own vue.config.js
as is shown below.
基本上,它在开发/生产模式下将 jquery 标记为外部,并在 test 模式下将其解析为模拟版本.创建一个 jquery 的模拟版本我会留给你.此示例改编自使用不同库的项目.
Basically, it marks jquery as an external in development/production mode, and resolves it to a mocked version in test mode. Creating a mocked-up version of jquery I'll leave to you though. This example was adapted from a project that uses a different library.
const path = require('path');
module.exports = {
configureWebpack() {
const isTest = process.env.NODE_ENV === 'test';
let resolve;
let externals = { jquery: 'jquery ' };
if (isTest) {
externals = {};
resolve = {
alias: {
// you may have to fiddle around with this path, from the point of view of where jquery is imported
jquery: './tests/helpers/fakeJQuery.js',
}
};
}
return {
resolve,
externals,
};
},
};
这篇关于模拟 webpack“外部"的正确方法(即 jquery)在 Vue 单元测试中(使用 mocha)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!