I have a project with TypeScript and React 0.14.
And I set-up test enviroment with karma/mocha/chai. And its work. But when I import and use function from enzyme I got error in browser (Human-readable error from Chrome):
Uncaught TypeError: ext[key].bind is not a function
As I understood modules 227...232 (internal DomUtils files) not loaded before using.
Maybe I forgot something? Or does anyone know workaround?
Sorry for huge configs:
Webpack config:
var webpack = require("webpack"),
path = require("path"),
ExtractTextPlugin = require("extract-text-webpack-plugin"),
precss = require('precss'),
autoprefixer = require('autoprefixer');
module.exports = {
entry: [
path.resolve(__dirname, "app/app.tsx")
],
output: {
filename: "bundle.js",
publicPath: "/build/",
path: path.resolve(__dirname, "build")
},
module: {
loaders: [
{test: /\.json$/, loader: 'json'},
{test: /\.tsx$/, exclude: /node_modules/, loader: 'es3ify!ts'},
{test: /\.s?css$/, loader: ExtractTextPlugin.extract('style', 'css!postcss')},
{test: /\.svg|eot|ttf|woff|woff2|ico|png|gif|jpg($|\?)/, loader: 'file'}
]
},
postcss: function () {
return [precss, autoprefixer];
},
resolve: {
root: path.resolve(__dirname, "app"),
extensions: ["", ".js", ".ts", ".tsx", ".json"]
},
plugins: [
new ExtractTextPlugin("bundle.css")
]
};
Karma config:
var webpack = require('webpack');
var webpackConfig = require('./webpack.config');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai', 'sinon'],
files: [
'app/**/*-test.tsx'
],
exclude: [],
preprocessors: {
'app/**/*.tsx': ['webpack']
},
webpack: {
resolve: webpackConfig.resolve,
module: webpackConfig.module,
externals: {
'cheereo': 'window',
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
},
reporters: ['progress', 'spec'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity
})
}
Test file:
import * as React from 'react';
import { shallow } from 'enzyme';
describe('Dashboard', () => {
it('should be OK', () => {
const instance = shallow(<div />);
expect(true).to.equal(true, 'true === true');
});
});
Webpack import chain: enzyme -> ... -> cheerio -> ... -> DomUtils
StackOverflow my last chance to solve the problem, Google don't know answer.
I've faced with same issue, for me it helps to put domutils as extrenal in webpack configuration. Based on your config try this:
webpack: {
resolve: webpackConfig.resolve,
module: webpackConfig.module,
externals: {
'domutils': 'true',
'cheereo': 'window',
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
}
Related
Why my react app fails on production build after upgrading to react 16 ?
After upgrading react to version 16 my app stoped working on production build, when running development works fine. If I downgrade to React 15.6 it still works fine on both prod and dev enviroments.
I am using: "webpack": "^3.5.6", and "react": "^16.0.0",
I am getting the following error:
Uncaught ReferenceError: require is not defined
My webpack prod configuration:
const path = require('path');
const merge = require("webpack-merge");
const webpack = require("webpack");
const config = require("./webpack.base.babel");
const OfflinePlugin = require('offline-plugin');
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = merge(config, {
// devtool: "nosources-source-map",
devtool: "source-map",
// In production, we skip all hot-reloading stuff
entry: [
'babel-polyfill', // Needed for redux-saga es6 generator support
path.join(process.cwd(), 'src/client/app.js'), // Start with app.js
],
performance: {
assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)),
},
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true
}),
new HtmlWebpackPlugin({
template: "src/client/index.html",
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
inject: true,
}),
// Shared code
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
children: true,
minChunks: 2,
async: true,
}),
// Avoid publishing files when compilation fails
new webpack.NoEmitOnErrorsPlugin(),
// Put it in the end to capture all the HtmlWebpackPlugin's
// assets manipulations and do leak its manipulations to HtmlWebpackPlugin
new OfflinePlugin({
relativePaths: false,
publicPath: '/',
// No need to cache .htaccess. See http://mxs.is/googmp,
// this is applied before any match in `caches` section
excludes: ['.htaccess'],
caches: {
main: [':rest:'],
// All chunks marked as `additional`, loaded after main section
// and do not prevent SW to install. Change to `optional` if
// do not want them to be preloaded at all (cached only when first loaded)
additional: ['*.chunk.js'],
},
// Removes warning for about `additional` section usage
safeToUseOptionalCaches: true,
AppCache: false,
}),
]
});
How can i fix it ?
webpack.base.babel.js
// Common Webpack configuration used by webpack.config.development and webpack.config.production
const path = require("path");
const webpack = require("webpack");
const autoprefixer = require("autoprefixer");
const e2c = require("electron-to-chromium");
const GLOBALS = require('../bin/helpers/globals');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const isProd = process.env.NODE_ENV === 'production';
const postcssLoaderOptions = {
plugins: [
autoprefixer({
browsers: e2c.electronToBrowserList("1.4")
}),
],
sourceMap: !isProd,
};
GLOBALS['process.env'].__CLIENT__ = true;
module.exports = {
target: 'web', // Make web variables accessible to webpack, e.g. window
output: {
filename: 'js/[name].[hash].js',
chunkFilename: 'js/[name].[hash].chunk.js',
path: path.resolve(process.cwd(), 'build'),
publicPath: "/"
},
resolve: {
modules: ["node_modules"],
alias: {
client: path.resolve(process.cwd(), "src/client"),
shared: path.resolve(process.cwd(), "src/shared"),
server: path.resolve(process.cwd(), "src/server")
},
extensions: [".js", '.jsx', ".json", ".scss"],
mainFields: ["browser", "module", 'jsnext:main', "main"],
},
plugins: [
new webpack.NormalModuleReplacementPlugin(
/\/Bundles.js/,
'./AsyncBundles.js'
),
new webpack.IgnorePlugin(/vertx/),
new webpack.ProvidePlugin({
Promise: 'imports-loader?this=>global!exports-loader?global.Promise!es6-promise',
fetch: "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch", // fetch API
$: "jquery",
jQuery: "jquery",
}),
new webpack.DefinePlugin(GLOBALS),
new ExtractTextPlugin({
filename: "css/[name].[hash].css",
disable: false,
allChunks: true
})
],
module: {
noParse: /\.min\.js$/,
rules: [
// JavaScript / ES6
{
test: /\.(js|jsx)?$/,
include: [
path.resolve(process.cwd(), "src/client"),
path.resolve(process.cwd(), "src/shared"),
],
exclude: /node_modules/,
use: "babel-loader"
},
// Json
{
test: /\.json$/,
use: 'json-loader',
},
//HTML
{
test: /\.html$/,
include: [
path.resolve(process.cwd(), "src/client"),
],
use: [
{
loader: "html-loader",
options: {
minimize: true
}
}
]
},
// Images
// Inline base64 URLs for <=8k images, direct URLs for the rest
{
test: /\.(png|jpg|jpeg|gif|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: "url-loader",
options: {
limit: 8192,
name: "images/[name].[ext]?[hash]"
}
}
},
// Fonts
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff'
}
}
},
{
test: /\.(ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader'
},
// Styles
{
test: /\.scss$/,
include: [
path.resolve(process.cwd(), "src/client"),
path.resolve(process.cwd(), "src/shared"),
],
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{
loader: "css-loader",
options: {
sourceMap: true,
modules: true,
importLoaders: 1,
localIdentName: '[local]_[hash:base64:3]'
}
},
{
loader: "postcss-loader",
options: postcssLoaderOptions
},
{
loader: "sass-loader",
options: {
sourceMap: true,
outputStyle: "compressed"
}
}
]
})
},
]
}
};
The fix was rly simple.
I just needed to remove this line noParse: /\.min\.js/
Which does :
Prevent webpack from parsing any files matching the given regular
expression(s). Ignored files should not have calls to import, require,
define or any other importing mechanism.
I am trying to make my first JS unit test with Karma and Jasmin. I am testing a react app.
I generated the karma config with "karma init" and modified it, see below for the karma.config.js
The webpack.config is required in the karma.config.js, but the babel loader is completely ignored, why?
I noticed it's ignored as it resulted in errors of undefined variable, etc...
When adding parts of the webpack.config.js directly in the karma.config.js (copy/paste), it works, but that is not what I want as I am duplicating code like my loaders and aliases, etc... How to solve this? See below also the webpack.config.js
The karma.config.js:
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: 'src/js/',
frameworks: ['jasmine'],
files: [
'tests/*.test.js',
],
preprocessors: {
'**/tests/*.test.js': ['webpack', 'sourcemap'],
},
webpack: require("../webpack.conf.js"),
webpackMiddleware: {
stats: "errors-only"
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
phantomJsLauncher: {exitOnResourceError: true},
singleRun: false,
concurrency: Infinity
})
};
The webpack.config.js:
module.exports = function (env) {
if (env !== undefined) {
let analyse = !!env.analyse;
console.log("Analyse?: " + analyse);
if (analyse) {
plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'}));
}
}
return {
entry: {
entry: ['./src/entry.js', './src/js/utils.js'],
},
devtool: devTool,
devServer: devServer,
output: {
path: __dirname + '/dist',
filename: '[name]-[hash].cache.js', // it contains the name ".cache", that is used in the webserver config.
sourceMapFilename: '[name]-[hash].cache.js.map',
},
module: {
rules: [
{ // The Babel loader:
test: /(\.jsx|\.js)$/,
exclude: /(node_modules|bower_components)/,
use: [{
loader: 'babel-loader',
options: {
presets: ['babel-preset-es2015', 'babel-preset-react'].map(require.resolve),
plugins: ['babel-plugin-transform-react-jsx-img-import'].map(require.resolve) // It will convert the used images to to "require" statements such that it's used by a loader below.
}
}]
},
{
test: /\.s?css$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|gif|jpe?g)$/,
use: [{
loader: 'file-loader',
options: {
name: 'resources/images/[name]-[hash]-cache.[ext]'
}
}]
},
{
test: /\.(otf|svg|eot|ttf|woff2?)(\?.*$|$)/,
use: [{
loader: 'file-loader',
options: {
name: 'resources/fonts/[name]-[hash]-cache.[ext]'
}
}]
},
]
},
plugins: plugins,
externals: ['axios'],
resolve: {
alias: {
// Ref: https://webpack.js.org/configuration/resolve/
Context: path.resolve(__dirname, 'src/js/context'),
Utils: path.resolve(__dirname, 'src/js/utils'),
....etc...
},
}
};
};
in karma.config.js:
webpack: require("../webpack.conf.js")
you're giving "webpack" a function instead of an object. you should immediately invoke it (with or without an env param) require("../webpack.conf.js")()
I am trying to execute jasmine test case of react+redux on webpack+karma background.
But getting below error
Below I have added webpack,karma config and react+redux component file.
1 ] karma.config.js
var webpackConfig = require('./webpack.config.js');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'app/assets/test/**/*Spec.js',
'app/assets/test/**/*Spec.jsx'
],
preprocessors: {
'app/assets/test/**/*Spec.js': ['webpack'],
'app/assets/test/**/*Spec.jsx': ['webpack']
},
webpack: webpackConfig,
reporters: ['kjhtml'],
port: 9876,
colors: true,
config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true,
concurrency: Infinity
})
}
2 ] react home.jsx component
import CarouselContainer from 'containers/carouselContainer'
import CurrentTracks from 'containers/currentTracks'
export default class Home extends React.Component {
render() {
return (
<div>
<CarouselContainer />
<CurrentTracks />
</div>
)
}
}
3 ] home.Spec.jsx -
import React from 'react';
import { shallow } from 'enzyme';
import ReactTestUtils from 'react-addons-test-utils'
import {Home} from 'pages/home'
describe("User suite", function() {
const wrapper = shallow(<Home/>);
expect(wrapper.length).toEqual(1);
});
4 ] Webpack.config.js -
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var merge = require('webpack-merge');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var BUILD = path.join(__dirname, 'build');
var APP = path.join(__dirname, 'app');
var JS = path.join(APP, 'assets', 'javascript');
var env = process.env.NODE_ENV;
console.log('Webpack env: ' + env)
var sassLoaders = [
'css-loader',
'postcss-loader',
'sass-loader?indentedSyntax=sass&includePaths[]=' + APP
];
var commonConfig = {
entry: [ path.join(JS, 'index.jsx') ],
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader'] },
{ test: /\.css/, loader: 'style-loader!css-loader?name=assets/css/[name]-[hash].[ext]' },
{ test: /\.png|jpg|gif$/, loader: 'file-loader?name=assets/images/[name]-[hash].[ext]' },
{ test: /\.xlsx$/, loader: 'file-loader?name=assets/file/[name].[ext]' },
{ test: /\.sass$/, loader: ExtractTextPlugin.extract('style-loader', sassLoaders.join('!')) },
{ test: /\.(woff|woff2|svg|ttf|eot|ico)$/, loader: 'file-loader?name=assets/fonts/[name].[ext]' }
]
},
output: {
filename: 'assets/javascript/[name]-[hash].js',
path: BUILD,
publicPath: '/'
},
externals: {
'jsdom': 'window',
'cheerio': 'window',
'react/lib/ExecutionEnvironment': true,
'react/addons': true,
'react/lib/ReactContext': 'window'
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html',
inject: 'body',
filename: 'index.html',
favicon: path.join(APP, 'assets', 'images', 'favicon.ico')
}),
new ExtractTextPlugin('assets/stylesheet/[name]-[hash].min.css'),
new CopyWebpackPlugin([
{ from: path.join(APP,'assets/javascript/vendor'), to: 'assets/vendor' }
]),
new CopyWebpackPlugin([
{ from: path.join(APP,'assets/test'), to: 'assets/test' }
]),
new webpack.ProvidePlugin({
React: "react",
"_": "lodash"
})
],
postcss: [
autoprefixer({
browsers: ['last 2 versions']
})
],
resolve: {
root: path.join(APP, 'assets'),
alias: {
config: '../../../../configs',
images: 'images',
actions: 'javascript/actions',
containers: 'javascript/containers',
components: 'javascript/components',
common: 'components/common',
constants: 'javascript/constants',
javascript: 'javascript',
layout: 'components/layout',
mywagers: 'pages/myWagers',
pages: 'components/pages',
home: 'pages/home',
utility: 'javascript/utility',
wagers: 'pages/wagers',
sheets: 'wagers/betPad/sheets'
},
extensions: ['', '.js', '.jsx', '.sass'],
modulesDirectories: ['app', 'node_modules']
}
};
var devConfig = {
devtool: 'inline-source-map',
entry: ['webpack-hot-middleware/client?reload=true'],
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env || 'development')
})
],
module: {
postLoaders: [
{
test: /\.js$/,
exclude: [/node_modules/,/vendor/],
loader: "jshint-loader"
}
]
}
};
var prodConfig = {
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env || 'production')
})
]
};
var config;
switch (env) {
case 'development':
config = merge(devConfig, commonConfig);
break;
default:
config = merge(prodConfig, commonConfig);
break;
}
module.exports = config;
It looks like Home is a default export, so in your spec on line 4, you should be importing as a default.
So the line should look like
import Home from 'pages/home';
instead of
import {Home} from 'pages/home';
When I run karma test with enzyme I get an error:
only one instance of babel-polyfill is allowed at ...
The is the test file that caused this error:
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../../src/common/store/configureStore';
import { shallow,mount } from 'enzyme';
import ChatContainer from '../../src/common/containers/ChatContainer';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
describe('ChatContainer Component', () => {
let Component;
beforeEach(() => {
Component =
mount(<Provider store={store}>
<ChatContainer />
</Provider>);
});
it('should render', () => {
expect(Component).toBeTruthy();
});
});
This is the only file so far that is triggering this error so I dont know why..
I am not sure if it is the babel-plugin-transform-class-properties in my karma config that is causing this issue:
/* eslint-disable no-var */
var path = require('path');
module.exports = function webpackConfig(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'test/components/*.spec.js',
// 'test/test_index.js',
],
preprocessors: {
'src/js/**/*.js': ['webpack', 'sourcemap'],
'test/**/*.spec.js': ['webpack', 'sourcemap'],
// 'test/test_index.js': ['webpack', 'sourcemap'],
},
webpack: {
devtool: 'inline-source-map',
alias: {
cheerio: 'cheerio/lib/cheerio',
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['airbnb'],
plugins: ["transform-class-properties"]
},
exclude: path.resolve(__dirname, 'node_modules'),
}, {
test: /\.json$/,
loader: 'json',
},
],
},
externals: {
cherrio: 'window',
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': 'window',
'react/addons': true,
},
},
webpackServer: {
noInfo: true,
},
plugins: [
'karma-webpack',
'karma-jasmine',
'karma-sourcemap-loader',
'karma-phantomjs-launcher',
'karma-spec-reporter',
'karma-chrome-launcher',
],
babelPreprocessor: {
options: {
presets: ['airbnb'],
},
},
reporters: ['spec'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
});
};
Here is my webpack config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'inline-source-map',
entry: [
'babel-polyfill',
'webpack-hot-middleware/client',
'./src/client/index'
],
output: {
path: path.resolve(__dirname, './static/dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
}
})
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
plugins: [,
[
'react-transform', {
transforms: [{
transform: ['react-transform-hmr']
imports: ['react'],
locals: ['module']
}, {
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react']
}]
}
]
]
},
include: [path.resolve(__dirname, 'src')]
},
{
test: /\.css?$/,
loaders: ['style', 'raw']
}
]
}
};
I've been using css-modules with mocha, enzyme and css-modules-require-hook without any problems.
Foo.js
import React from 'react';
import styles from './Foo.css';
const Foo = () => <div className={ styles.foo }>Foo component</div>;
export default Foo;
Foo.css
.foo {
color: rebeccapurple;
}
Foo.test.js
import Foo from './Foo';
describe('<Foo />', () => {
it('should render proper markup', () => {
const wrapper = shallow(<Foo />);
expect(wrapper.find('.foo')).to.have.length(1);
});
});
I started using Karma with karma-webpack-with-fast-source-maps and now the test fails because the styles in Foo.js is an array and it's not using keys to keep original class name.
[[376, '.Foo__foo___3QT3e {
color: rebeccapurple;
}
', '']]
I've tried importing the css-modules-require-hook in test-bundler.js for karma-webpack but that throws a bunch of errors.
WARNING in ./~/css-modules-require-hook/preset.js
Critical dependencies:
13:7-22 the request of a dependency is an expression
# ./~/css-modules-require-hook/preset.js 13:7-22
// many more warnings
ERROR in ./~/css-modules-require-hook/lib/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/qmmr/code/streetlife/composer/code/site/node_modules/css-modules-require-hook/lib
# ./~/css-modules-require-hook/lib/index.js 14:19-32
// more errors
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
SyntaxError: Unexpected token ')'
webpack.config.test.js
/* eslint-disable */
var path = require('path');
const CSS_MODULES_LOADER = [
'modules',
'importLoaders=1',
'localIdentName=[name]__[local]___[hash:base64:5]'
].join('&');
module.exports = {
resolve: {
extensions: [ '', '.js' ],
},
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
cacheDirectory: true,
plugins: [ 'transform-runtime', 'transform-class-properties', 'transform-export-extensions' ],
presets: [ 'es2015', 'react', 'stage-2' ],
}
},
{
test: /\.css$/,
loader: `css?${ CSS_MODULES_LOADER }`,
include: path.join(__dirname, '/css/modules'),
},
{ test: /\.json$/, loader: 'json' },
],
},
externals: {
'cheerio': 'window',
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
},
};
karma.conf.js
// Karma configuration
var webpackConfig = require('./webpack.config.test');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: [ 'mocha' ],
plugins: [
'karma-mocha',
'karma-phantomjs-launcher',
'karma-webpack-with-fast-source-maps'
],
files: [
{
pattern: './testBundler.js',
watched: false,
served: true,
included: true,
},
],
exclude: [],
preprocessors: {
[ './test-bundler.js' ]: [ 'webpack' ]
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
stats: 'errors-only',
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [ 'PhantomJS' ],
singleRun: true,
concurrency: Infinity,
})
}
test-bundler.js
// ---------------------------------------
// Test Environment Setup
// ---------------------------------------
import React from 'react';
import chai from 'chai';
import sinon from 'sinon';
import { shallow, mount } from 'enzyme';
// require('css-modules-require-hook/preset'); // Fix css-modules not rendering in tests
global.React = React;
global.expect = chai.expect;
global.sinon = sinon;
global.shallow = shallow;
global.mount = mount;
// ---------------------------------------
// Require Tests
// ---------------------------------------
// for use with karma-webpack-with-fast-source-maps
const __karmaWebpackManifest__ = new Array(); // eslint-disable-line
const inManifest = (path) => ~__karmaWebpackManifest__.indexOf(path);
const testsContext = require.context('../react', true, /\.test\.js$/);
// only run tests that have changed after the first pass.
const testsToRun = testsContext.keys().filter(inManifest);
(testsToRun.length ? testsToRun : testsContext.keys()).forEach(testsContext);
How can I use css-modules-require-hook in my setup (karma + webpack)?
EDIT: I've created a repository https://github.com/qmmr/yab to show the issue. When running npm run test:mocha the test passes. When running npm run test it fails (this is the karma-webpack integration).