在mocha测试中使用webpack别名

时间:2015-11-19 01:05:46

标签: reactjs npm mocha webpack redux

我正在React / Redux / Webpack中开发一个Web应用程序,现在我开始将测试与Mocha集成。

我关注the instructions for writing tests in the Redux documentation,但现在我的网络包别名遇到了问题。

例如,请查看我的一个动作创建者的此测试的导入部分:

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在引用别名依赖项时无法解析我的import语句。

因为我还是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中。

8 个答案:

答案 0 :(得分:37)

好的,所以我意识到我所有的别名都在return(x) 目录中,所以我只需要修改我的src/脚本。

npm run test

可能不适合所有人,但这解决了我的问题。

答案 1 :(得分:15)

您还可以使用我撰写的babel插件: https://github.com/trayio/babel-plugin-webpack-alias 只需在您的.babelrc中添加一个babel插件,它就会将您的别名路径转换为相对路径。

答案 2 :(得分:4)

我也遇到了同样的问题,但是通过这个插件,我解决了它。

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

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

npm i -D babel-plugin-webpack-aliases

并将此设置添加到.babelrc

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

答案 3 :(得分:3)

丹尼的回答很棒。但我的情况有点不同。 我使用了webpack' resolve.alias来使用src文件夹下的所有文件。

resolve: {
  alias: {
    '-': path.resolve(__dirname, '../src'),
  },
},

并为我自己的模块使用一个特殊的前缀:

import App from '-/components/App';

测试这样的代码 我必须在mocha测试之前添加一个命令ln -sf src test/alias/-,然后使用Danny阵营的NODE_PATH=./test/alias技巧。所以最终的脚本将是这样的:

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

PS:

我使用-因为@~这样的美化角色不够安全。我找到了安全字符here

的答案

答案 4 :(得分:2)

我想我解决了这个问题。您应该使用2个包: mock-require proxyquire

假设你有一个像这样的js文件:

<强> app.js

import action1 from 'actions/youractions';   

export function foo() { console.log(action1()) }; 

你的测试代码应该这样写:

<强> app.test.js

import proxyquire from 'proxyquire';
import mockrequire from 'mock-require';

before(() => {
  // mock the alias path, point to the actual path
  mockrequire('actions/youractions', 'your/actual/action/path/from/your/test/file');
  // or mock with a function
  mockrequire('actions/youractions', {actionMethod: () => {...}));

let app;
beforeEach(() => {
  app = proxyquire('./app', {});
});

//test code
describe('xxx', () => {
  it('xxxx', () => {
    ...
  });
});

文件树

app.js
  |- test
    |- app.test.js

首先在函数之前通过mock-require模拟别名路径,然后在beforeEach函数中通过proxyquire模拟测试对象。<​​/ p>

答案 5 :(得分:2)

我假设你--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"
       }
    }]
  ]
}

答案 6 :(得分:1)

我有完全相同的问题。似乎不可能在require.js或节点的require中使用webpack别名。

我最终在单元测试中使用mock-require,只是手动替换路径,如下所示:

var mock = require('mock-require');

mock('actions/app', '../../src/actions/app');

mock-require是一个很好的工具,因为您最有可能想要模拟大部分依赖项,而不是使用src中的实际脚本。

答案 7 :(得分:0)

要将别名保留在config/webpack.common.js之类的位置

resolve: {
    alias: {
        '~': path.resolve(__dirname, './../src/app')
    }
}

然后安装babel-plugin-webpack-alias

npm i babel-plugin-webpack-alias --save-dev

然后将.babelrc中的内容放入:

{
    "presets": ["env"],
    "plugins": [
        ["babel-plugin-webpack-alias", {
            "config": "./config/webpack.common.js" // path to your webpack config
        }]
    ]
}