我正在使用 React/Redux/Webpack 开发一个 Web 应用程序,现在开始与 Mocha 集成测试。
我关注了the instructions for writing tests in the Redux documentation ,但现在我的 webpack 别名遇到了问题。
例如,看看我的一位 Action 创建者的此测试的导入部分:
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);
});
});
});
正如评论所暗示的,当我的 import 语句引用别名依赖项时,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 中。
最佳答案
好吧,我意识到我别名的所有内容都在 src/
目录中,所以我只需要修改我的 npm run test
脚本即可。
{
"scripts": {
"test": "NODE_PATH=./src mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
}
}
可能并不适合所有人,但这解决了我的问题。
关于reactjs - 在 mocha 测试中使用 webpack 别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793504/