我正在使用Karma + Mocha + Chai + Webpack运行测试。我想将多个Chai插件应用到我的测试中。我使用下面的Karma配置,它将我的测试分成多个包。
我尝试使用karma-chai创建一个全局chai实例,然后加载将插件应用到全局实例的代码。(请参阅CHAI_CONFIG_PATH和plugins.config.js):
// karma.config.babel.js
import WEBPACK_CONFIG from '../webpack/webpack.config.test';
const TESTS_PATH = 'src/**/*.test.js';
const CHAI_CONFIG_PATH = 'config/chai/*.js';
export default function(config) {
config.set({
autoWatch: false,
singleRun: !autoWatch,
browsers: ['PhantomJS'],
basePath: '../..',
frameworks: ['mocha', 'chai'],
files: [
require.resolve('babel-polyfill'),
CHAI_CONFIG_PATH
TESTS_PATH
],
preprocessors: {
[require.resolve('babel-polyfill')]: ['webpack'],
[CHAI_CONFIG_PATH]: ['webpack'],
[TESTS_PATH]: ['webpack', 'sourcemap']
},
webpack: WEBPACK_CONFIG,
webpackMiddleware: {
noInfo: true
},
reporters: ['mocha'],
logLevel: config.LOG_INFO
});
}应用chai插件:
// 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配置:
// 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'
};在我添加chai-enzyme之前,它一直起作用。config/chai/plugins.config.js在加载enzyme的自己的捆绑包中运行。我的测试是在另一个包中运行的,它再次加载enzyme。这两个enzyme并不相同。chai-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插件应用到每个包?
发布于 2017-08-23 16:36:13
我也遇到过类似的问题。我没有找到一个完美的解决方案,但至少为我的情况找到了一个变通办法:
我围绕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} from './my-expect'替换了以前的import {expect} from 'chai',以使用我在那里包括的所有插件:
// my_spec.ts
import {expect} from './my-expect';
it('should use chai-things', () => {
expect([5, 7, 9]).to.all.be.above(4);
});https://stackoverflow.com/questions/42729765
复制相似问题