【问题标题】:How do I apply Chai plugins across bundles in Karma?如何在 Karma 中跨包应用 Chai 插件?
【发布时间】:2017-03-11 00:08:04
【问题描述】:

我正在使用 Karma + Mocha + Chai + Webpack 运行测试。我想在我的测试中应用多个 Chai 插件。我正在使用下面的 Karma 配置,它将我的测试分成多个包。

我尝试使用karma-chai 创建一个全局chai 实例,然后加载将插件应用到全局实例的代码。 (见CHAI_CONFIG_PATHplugins.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。两个enzymes 不一样。 chai-enzyme 在每个断言上运行 wrap(myShallowWrapper),但 el instanceof ShallowWrapper 为假。

// chai-enzyme/src/wrap.js
export default function wrap (el) {
  if (el instanceof ShallowWrapper) {
    return new ShallowTestWrapper(el)
  }
  ...
}

我希望将捆绑包分开,以便更轻松地开发测试。我发现的唯一解决方法是在每个测试文件的顶部导入plugins.config.js,但这似乎很麻烦。有没有可以让我将 Chai 插件应用到每个包的配置?

【问题讨论】:

    标签: webpack mocha.js karma-runner chai chai-enzyme


    【解决方案1】:

    我遇到了类似的问题。我没有找到完美的解决方案,但至少是我的情况的解决方法:

    我围绕需要包含在任何测试用例中的期望导入构建了自己的包装器。这样我就可以在一个中心位置配置我所有使用过的 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 'chai' 替换为 import {expect} from './my-expect' 即可使用我在其中包含的所有插件:

    // my_spec.ts
    import {expect} from './my-expect';
    
    it('should use chai-things', () => {
      expect([5, 7, 9]).to.all.be.above(4);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多