我正在使用React / Redux / Webpack开发一个可运行的Web应用程序,现在开始将测试与Mocha集成在一起。
我遵循Redux文档中有关编写测试的说明,但是现在我的webpack别名遇到了问题。
例如,看看我的动作创建者之一的此测试的imports部分:
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在引用别名依赖项时无法解析我的导入语句。
因为我还是Webpack的新手,所以这是我的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
。
{
"scripts": {
"test": "mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
}
}
所以这就是我卡住的地方。我需要在运行时将webpack的别名包含到mocha中。
我想你会
--require babel-register
在你的mocha.opts
。您可以使用babel模块解析器插件https://github.com/tleunen/babel-plugin-module-resolver。这允许您在.babelrc中设置别名,类似于您的webpack别名: