使用带有Mocha测试的webpack插件

Dón*_*nal 12 mocha.js reactjs webpack

我使用create-react-app创建了一个应用程序,并弹出了配置.在webpack.config.dev.jswebpack.config.prod.js,我已经配置了 NormalModuleReplacementPlugin这样:

new webpack.NormalModuleReplacementPlugin(/(.*)CUSTOMER(\.*)/, function(resource) {
  const customerName = process.env.REACT_APP_CUSTOMER;
  resource.request = resource.request.replace(/CUSTOMER/, customerName);
})
Run Code Online (Sandbox Code Playgroud)

这样做的目的是替换诸如的进口

import config from '../config/customer/CUSTOMER';
Run Code Online (Sandbox Code Playgroud)

import config from '../config/customer/foo';
Run Code Online (Sandbox Code Playgroud)

REACT_APP_CUSTOMER变量的值设置为"foo"时.

当应用程序运行时,这可以正常工作,但我有一些通过test-mocha脚本运行的Mocha测试package.json

"scripts": {
  "test-mocha": "NODE_ENV=test node_modules/.bin/mocha --require babel-register --recursive test"
}
Run Code Online (Sandbox Code Playgroud)

此测试运行时,不会发生导入替换.似乎以下任何一种都可以解决问题:

  • 配置NormalModuleReplacementPlugin运行测试时使用的
  • 找到一种方法来为config测试运行时提供模拟

str*_*tss 5

看一下mocha-webpack。如文档中所述,它基本上webpack test.js output.js && mocha output.js进行了一些优化。因此,之后npm i -D mocha-webpack,您scripts应该看起来像:

"scripts": {
  "test-mocha": "NODE_ENV=test node_modules/.bin/mocha-webpack --recursive test"
}
Run Code Online (Sandbox Code Playgroud)

您可以尝试的另一种选择是利用模拟node.js模块负责的模拟需求。在您的情况下,您需要mock-helper.js

"test-mocha": "NODE_ENV=test node_modules/.bin/mocha -r babel-register -r ./test/mock-helper.js --recursive test"

并且./test/mock-helper.js应该是这样的:

const mock = require('mock-require');
const defaultCustomer = require('../config/customer/default');
const fooCustomer = require('../config/customer/foo');

const customerMock = (function () {
  switch (process.env.REACT_APP_CUSTOMER) {
    case 'foo': return fooCustomer;
    default: return defaultCustomer;
  }
}())

mock('../config/customer/CUSTOMER', customerMock);
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。


Dón*_*nal 3

我选择了一个简单/明显的解决方案:

config/customer/CUSTOMER.js创建一个包含最低预期配置的虚拟文件,例如

export default {
  customerName: 'Dummy'
}
Run Code Online (Sandbox Code Playgroud)

运行测试时,导入例如

import config from '../config/customer/CUSTOMER';
Run Code Online (Sandbox Code Playgroud)

将不再失败,因为该模块现在存在。