簡體   English   中英

如何在Karma的捆綁中應用Chai插件?

[英]How do I apply Chai plugins across bundles in Karma?

我正在使用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);

Vanilla 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在它自己的bundle中運行,它加載了enzyme 我的測試是在另一個捆綁中運行,再次加載enzyme 這兩種enzyme不一樣。 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插件應用於每個捆綁包?

我遇到了類似的問題。 我沒有找到一個完美的解決方案,但至少我的案例有一個解決方法:

我圍繞期望導入構建了自己的包裝器,無論如何都需要包含在任何測試用例中。 這樣我可以在一個中心位置配置我所有使用過的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'替換import {expect} from 'chai'的前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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM