Testing 带require模块的Jest全局变量
我正在为一个非常小的vanilla js库做一些测试,所以我有这个模块Testing 带require模块的Jest全局变量,testing,webpack,jestjs,Testing,Webpack,Jestjs,我正在为一个非常小的vanilla js库做一些测试,所以我有这个模块 var otherModule = require('../module/mymodule'); var postscribe = require('postscribe'); var exports = module.exports = {}; var API_URL = URL; exports.myFunction = function (arg1, arg2, arg3) { if (arg1 &&a
var otherModule = require('../module/mymodule');
var postscribe = require('postscribe');
var exports = module.exports = {};
var API_URL = URL;
exports.myFunction = function (arg1, arg2, arg3) {
if (arg1 && arg2) {
var myUrl = getApiUrl(arg1, arg2, arg3);
callSomeURL(myUrl);
}
}
function getApiUrl(arg1, arg2, arg3) {
var param1 = otherModule.getParams(arg1);
var param2 = otherModule.getOtherParams(arg1);
return `${API_URL}/v1/pixels/${arg1}/${arg2}${param1}${param2}`;
}
...
然后我有其他模块和我的函数
var GLOBAL_VALUE = MY_VALUE;
var otherModule = {};
otherModule.getParams = function (arg1) {
return arg1 ? `&value=${arg1}` : '';
}
otherModule.getOtherParams = function (arg1) {
return GLOBAL_VALUE + arg1
}
module.exports = otherModule;
我的网页配置
const { DefinePlugin } = require('webpack');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const devConfig = require('./src/config/dev');
module.exports = () => {
var envConfig = devConfig;
return merge(common, {
mode: 'development',
devtool: 'inline-source-map',
plugins: [
new DefinePlugin({
__DEV__: true,
URL: JSON.stringify(envConfig.URL),
MY_VALUE: JSON.stringify(envConfig.VALUE)
})
]
})
}
我的共同点是:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
plugins: [
new CleanWebpackPlugin()
],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
还有我的jest.config
const config = require('./src/config/dev');
module.exports = {
globals: {
"MY_VALUE": config.VALUE,
"URL" : config.URL
}
}
当我试图通过rewire测试exports.myFunction以访问私有函数getApiUrl时,我的问题出现了。似乎我无法访问导入的全局值,如全局值
在我的myOther中,我不断得到引用错误:全局值没有定义,但当我直接测试myOther模块时,一切似乎都正常,有人能告诉我我做错了什么吗?
var GLOBAL\u VALUE=GLOBAL\u VALUE
没有意义,因为它总是未定义的。变量名应该不同。Rewire与Jest不兼容,因为它们使用相同的技巧滥用节点模块,这可能是您提到的错误的原因之一。如果您想使其可测试,请使用不依赖黑客的常用方法。至于getApiUrl,情况与相同。我在编辑代码以使其可读时犯了错误,我对每个值使用了不同的名称。已经编辑了这个问题。谢谢埃斯特斯