在Mocha测试中使用Webpack别名 [英] Using webpack aliases in mocha tests
问题描述
我正在使用React/Redux/Webpack开发一个工作中的Web应用程序,现在开始将测试与Mocha集成.
I'm developing a web app at work in React/Redux/Webpack and am now starting to integrate testing with Mocha.
我遵循了 Redux文档中编写测试的说明,但是现在我的webpack别名遇到了问题.
I followed the instructions for writing tests in the Redux documentation, but now I have run into an issue with my webpack aliases.
例如,看看我的动作创建者之一的本次测试的导入"部分:
For example, take a look at the imports section of this test for one of my action creators:
import expect from 'expect' // resolves without an issue
import * as actions from 'actions/app'; // can't resolve this alias
import * as types from 'constants/actionTypes'; // can't resolve this alias
describe('Actions', () => {
describe('app',() => {
it('should create an action with a successful connection', () => {
const host = '***************',
port = ****,
db = '******',
user = '*********',
pass = '******';
const action = actions.createConnection(host, port, db, user, pass);
const expectedAction = {
type: types.CREATE_CONNECTION,
status: 'success',
payload: { host, port, database, username }
};
expect(action).toEqual(expectedAction);
});
});
});
正如评论所建议的那样,mocha在引用别名依赖项时无法解析我的导入语句.
As the comments suggest, mocha isn't able to resolve my import statements when they are referencing aliased dependencies.
因为我还是Webpack的新手,所以这是我的webpack.config.js
:
Because I'm still new to webpack, here's my webpack.config.js
:
module.exports = {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
extensions : ['', '.js', '.jsx'],
alias: {
actions: path.resolve(__dirname, 'src', 'actions'),
constants: path.resolve(__dirname, 'src', 'constants'),
/* more aliases */
}
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname
}]
}
};
此外,我正在使用命令npm test
来运行mocha,这是我在package.json
中使用的脚本.
Also, I'm using the command npm test
to run mocha, here's the script I'm using in my package.json
.
{
"scripts": {
"test": "mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
}
}
所以这就是我被卡住的地方. 我需要在运行时将webpack的别名包含到mocha中.
So here's where I get stuck. I need to include the aliases from webpack into mocha when it runs.
推荐答案
好的,所以我意识到我所别名的东西都在src/
目录中,所以我只需要修改我的npm run test
脚本即可.
Okay so I realized that everything I was aliasing was in the src/
directory, so I simply needed to modify my npm run test
script.
{
"scripts": {
"test": "NODE_PATH=./src mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
}
}
可能不是所有人都可以使用,但这解决了我的问题.
Probably won't work for everyone, but that solved my issue.
这篇关于在Mocha测试中使用Webpack别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!