在Mocha测试中使用Webpack别名

reactjs Webpack

神乐凯

2020-03-23

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

第3116篇《在Mocha测试中使用Webpack别名》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
村村猴子 2020.03.23

我想你会--require babel-register在你的mocha.opts您可以使用babel模块解析器插件https://github.com/tleunen/babel-plugin-module-resolver这允许您在.babelrc中设置别名,类似于您的webpack别名:

{
  "plugins": [
    ["module-resolver", {
       "alias": {
         "actions": "./src/actions",
         "constants": "./src/constants"
       }
    }]
  ]
}
老丝阿飞 2020.03.23

我也遇到了同样的问题,但是使用此插件,我解决了它。

https://www.npmjs.com/package/babel-plugin-webpack-aliases

您的“ mocha”的执行命令未读取webpack.config.js,因此无法解析别名。
通过设置此插件,请webpack.config.js在使用“ babel-core / register”进行编译时考虑结果,别名在测试期间也将有效。

npm i -D babel-plugin-webpack-aliases

并将此设置添加到 .babelrc

{
    "plugins": [
        [ "babel-plugin-webpack-aliases", { "config": "./webpack.config.js" } ] 
    ]
}
小宇宙 2020.03.23

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

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

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

樱小胖Mandy 2020.03.23

您还可以使用我编写的babel插件:https : //github.com/trayio/babel-plugin-webpack-alias 只需将babel插件包含到,它就可以将别名路径转换为相对路径.babelrc

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android