Webpack 如何在Karma中跨包应用Chai插件?
我正在使用Karma+Mocha+Chai+Webpack进行测试。我想在我的测试中应用多个Chai插件。我正在使用下面的Karma配置,它将我的测试分成多个包 我尝试使用Webpack 如何在Karma中跨包应用Chai插件?,webpack,mocha.js,karma-runner,chai,chai-enzyme,Webpack,Mocha.js,Karma Runner,Chai,Chai Enzyme,我正在使用Karma+Mocha+Chai+Webpack进行测试。我想在我的测试中应用多个Chai插件。我正在使用下面的Karma配置,它将我的测试分成多个包 我尝试使用karma chai创建一个全局chai实例,然后加载将插件应用到全局实例的代码。(请参见CHAI_CONFIG_PATH和plugins.CONFIG.js): 应用程序插件: // config/chai/plugins.config.js import chaiImmutable from 'chai-immutable
karma chai
创建一个全局chai
实例,然后加载将插件应用到全局实例的代码。(请参见CHAI_CONFIG_PATH
和plugins.CONFIG.js
):
应用程序插件:
// config/chai/plugins.config.js
import chaiImmutable from 'chai-immutable';
import chaiEnzyme from 'chai-enzyme';
import chaiSinon from 'chai-sinon';
chai.use(chaiImmutable);
chai.use(chaiEnzyme());
chai.use(chaiSinon);
普通网页包配置:
// webpack.config.tests.js
export default {
module: {
rules: [
BABEL_LOADER,
CSS_LOADER,
CSS_LOADER_GLOBALS,
JSON_LOADER,
MEDIA_FILE_LOADER,
MEDIA_URL_LOADER
]
},
plugins: [
DEFINE_PLUGIN,
EXTRACT_TEXT_PLUGIN
],
devtool: 'inline-source-map'
};
在我添加之前,它一直有效config/chai/plugins.config.js
在它自己的包中运行,它加载enzyme
。我的测试在另一个包中运行,它再次加载enzyme
。这两种酶不一样<代码>对每个断言运行wrap(myShallowWrapper)
,但el instanceof ShallowWrapper
为false
// chai-enzyme/src/wrap.js
export default function wrap (el) {
if (el instanceof ShallowWrapper) {
return new ShallowTestWrapper(el)
}
...
}
我希望将捆绑包分开,以使开发测试更容易。我找到的唯一修复方法是在每个测试文件的顶部导入plugins.config.js
,但这似乎有点不对劲。是否有一种配置可以让我将Chai插件应用于每个捆绑包?我遇到了类似的问题。我没有找到一个完美的解决方案,但至少为我的案例找到了解决办法:
我围绕expect导入构建了自己的包装器,该导入无论如何都需要包含在任何测试用例中。这样,我就可以在一个中心位置配置所有使用过的chai插件:
// my-expect.ts:
import {expect as _expect} from 'chai';
import * as chai from 'chai';
chai.use(require('chai-things'));
chai.use(require('chai-string'));
export const expect = _expect;
在我现在的测试中,我只需将以前的import{expect}从'chai'
替换为import{expect}从'./my expect'
来使用我在其中包含的所有插件:
// my_spec.ts
import {expect} from './my-expect';
it('should use chai-things', () => {
expect([5, 7, 9]).to.all.be.above(4);
});
// my_spec.ts
import {expect} from './my-expect';
it('should use chai-things', () => {
expect([5, 7, 9]).to.all.be.above(4);
});