小编典典

在Mocha测试中使用Webpack别名

reactjs

我正在使用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中。


阅读 275

收藏
2020-07-22

共1个答案

小编典典

好的,我意识到我所别名的所有东西都在src/目录中,因此我只需要修改npm run test脚本即可。

{   
  "scripts": {
    "test": "NODE_PATH=./src mocha ./src/**/test/spec.js --compilers js:babel-core/register --recursive"
  }
}

可能对每个人都行不通,但这解决了我的问题。

2020-07-22