Path is a file error loading tests with Karma and Webpack - karma-runner

I am trying to setup the Karma test runner on a webpack project I am working on. I have a few test files that I tried to include but Karma keeps on giving me Error: Path is a file '/_karma_webpack_/app/w/tests/components'. Why does MemoryFileSystem fail with this message? All help is appreciated.
My karma.conf.js:
//Require webpack config rather than duplicating it
var webpackConfig = require('./webpack.config');
webpackConfig.devtool = 'inline-source-map';
module.exports = function(config) {
config.set({
basePath:'',
browsers: ['Chrome_without_sandbox'], // Note: PhantomJS has too outdated WebKit, pre ES5, to work with Browserify
singleRun: true,
customLaunchers: {
Chrome_without_sandbox: {
base: 'Chrome',
flags: ['--no-sandbox'] // w/ sandbox it fails under Docker
}
},
frameworks: ['mocha'],
files: ['./app/w/tests/**/*-test.js'],
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
preprocessors: {
'./app/w/tests/**/*-test.js' : ['webpack']
}
});
};
I tried loading files with require.context and bundle them, but the result is the same.. so I figured the issue could be with what MemoryFileSystem expects as input.
webpack.config.js
var webpack = require('webpack');
var bower_dir = __dirname + '/bower_components';
var config = {
//devtool: 'cheap-module-eval-source-map',
devtool: 'eval',
entry: {
app: ['webpack/hot/dev-server', './app/w/scripts/app.js']
},
resolve: { alias: {} },
output: {
path: './app/w/dist',
filename: 'app.js',
publicPath: '/dist/'
},
module: {
noParse: [],
loaders: [
{ test: /\.js$/, loader: 'eslint!babel?optional[]=runtime', exclude: /node_modules/},
{ test: /\.json$/, loader: 'json'},
{ test: /\.png$/, loader: "url?limit=10000&mimetype=image/png" },
{ test: /\.woff$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot$/, loader: "file" },
{ test: /\.svg$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
{ test: /\.less/, loader: 'style!css!less'}
]
},
plugins: new webpack.optimize.UglifyJsPlugin({
minimize: true,
sourceMap: false,
})
};
module.exports = config;
Error log:
ERROR [karma]: [Error: Path is a file '/_karma_webpack_/app/w/tests/components']
Error: Path is a file '/_karma_webpack_/app/w/tests/components'
at MemoryFileSystem.mkdirpSync (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/karma-webpack/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:116:10)
at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/karma-webpack/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:193:34)
at Tapable.<anonymous> (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/lib/Compiler.js:244:27)
at /Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/node_modules/async/lib/async.js:187:20
at /Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/node_modules/async/lib/async.js:239:13
at _arrayEach (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/node_modules/async/lib/async.js:91:13)
at _each (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/node_modules/async/lib/async.js:82:13)
at Object.async.forEachOf.async.eachOf (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/node_modules/async/lib/async.js:238:9)
at Object.async.forEach.async.each (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/node_modules/async/lib/async.js:215:22)
at Tapable.emitFiles (/Users/magnuslien/Documents/internprosjekter/woop-frontend/node_modules/webpack/lib/Compiler.js:234:20)
package.json
"devDependencies": {
"babel-loader": "^5.3.2",
"browserify": "^11.0.1",
"karma": "^0.12.31",
"karma-chrome-launcher": "^0.2.0",
"karma-mocha": "^0.2.0",
"karma-sourcemap-loader": "^0.3.5",
"karma-webpack": "^1.7.0",
"mocha": "^2.2.5",
"proxyquireify": "^3.0.0",
"webpack": "^1.11.0",
"webpack-dev-server": "^1.10.1"
}

I had the same problem.
Somehow the webpack.config.js is not allowed to have the entry app.
Add
webpackConfig.entry = {};
just under the line
webpackConfig.devtool = 'inline-source-map'; in your karma.conf.js
This worked for me

Related

"before each" hook: codeceptjs error message

im using codeceptjs using protractor helper, and i tried to wtite simple code
and to run this command"npm run codeceptjs"
and i faced this error "× "before each" hook: codeceptjs.before for "test something" in 285ms"
here is my code on this file "test_test.js"
Feature('My First Test');
Scenario('test something', ({ I }) => {
I.amOnPage('/');
I.see('GitHub');
});
here package.json
{
"name": "codeceptjs-tests",
"version": "0.1.0",
"private": true,
"scripts": {
"codeceptjs": "codeceptjs run --steps",
"codeceptjs:headless": "HEADLESS=true codeceptjs run --steps",
"codeceptjs:ui": "codecept-ui --app",
"codeceptjs:demo": "codeceptjs run --steps -c node_modules/#codeceptjs/examples",
"codeceptjs:demo:headless": "HEADLESS=true codeceptjs run --steps -c
node_modules/#codeceptjs/examples",
"codeceptjs:demo:ui": "codecept-ui --app -c node_modules/#codeceptjs/examples"
},
"devDependencies": {
"#codeceptjs/configure": "^0.8.0",
"#codeceptjs/examples": "^1.2.1",
"#codeceptjs/ui": "^0.4.6",
"codeceptjs": "^3.0.0",
"playwright": "^1.19.2",
"protractor": "^5.3.0"
}
}
here codecept.conf.js file
const { setHeadlessWhen } = require('#codeceptjs/configure');
// turn on headless mode when running with HEADLESS=true environment variable
// export HEADLESS=true && npx codeceptjs run
setHeadlessWhen(process.env.HEADLESS);
exports.config = {
tests: './*_test.js',
output: './output',
helpers: {
Protractor: {
url: 'http://www.github.com',
driver: 'hosted',
browser: 'chrome',
rootElement: 'body',
angular: false
}
},
include: {
I: './steps_file.js'
},
bootstrap: null,
mocha: {},
name: 'Task1',
plugins: {
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
tryTo: {
enabled: true
},
screenshotOnFail: {
enabled: true
}
}
}
how could i fix the issue?
Error seems to be related to the selenium server. You can see details on https://github.com/codeceptjs/CodeceptJS/issues/2634
Please follow the steps on codecept website for project setup
https://codecept.io/angular/#setting-up-codeceptjs-with-protractor

Rollup.js building error with material-ui layout-grid component included

I integrated Material UI into my Svelte project with help of "Svelte Material UI" package.
But it don't contains Material layout-grid component.
I installed it separately using yarn add "#material/layout-grid" command.
But now I'm getting error during build process:
[!] (plugin postcss) Error: Invalid CSS after "...ch $size in map": expected expression (e.g. 1px, bold), was ".keys(variables.$co"
node_modules/#material/layout-grid/mdc-layout-grid.scss
Error: Invalid CSS after "...ch $size in map": expected expression (e.g. 1px, bold), was ".keys(variables.$co"
at options.error (/media/hdd-home/d/WebServers/home/spadmin.org/public_html/todoapp/node_modules/node-sass/lib/index.js:291:26)
So, I gave up resolving it myself.
The project package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv ."
},
"devDependencies": {
"#mdi/js": "^5.3.45",
"#rollup/plugin-commonjs": "^12.0.0",
"#rollup/plugin-node-resolve": "^8.0.0",
"#smui/button": "^1.0.0-beta.21",
"#smui/card": "^1.0.0-beta.21",
"#smui/checkbox": "^1.0.0-beta.21",
"#smui/chips": "^1.0.0-beta.21",
"#smui/common": "^1.0.0-beta.21",
"#smui/form-field": "^1.0.0-beta.21",
"#smui/linear-progress": "^1.0.0-beta.21",
"#smui/textfield": "^1.0.0-beta.21",
"#smui/top-app-bar": "^1.0.0-beta.21",
"material": "^0.4.3",
"node-sass": "^4.14.1",
"rollup": "^2.3.4",
"rollup-plugin-copy": "^3.3.0",
"rollup-plugin-livereload": "^1.0.0",
"rollup-plugin-postcss": "^3.1.1",
"rollup-plugin-svelte": "^5.0.3",
"rollup-plugin-terser": "^5.1.2",
"svelte": "^3.0.0",
"svelte-preprocess": "^3.7.4"
},
"dependencies": {
"#material/layout-grid": "^6.0.0",
"sirv-cli": "^0.4.4"
}
}
And here is rollup.config.js
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import copy from 'rollup-plugin-copy';
import livereload from 'rollup-plugin-livereload';
import {terser} from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss';
import autoPreprocess from 'svelte-preprocess';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'scripts/app.js',
},
plugins: [
copy({
targets: [
{src: 'src/index.html', dest: '.'},
],
}),
svelte({
dev: !production,
emitCss: true,
css: css => {
css.write('css/app.css');
},
preprocess: autoPreprocess()
}),
resolve({
browser: true,
dedupe: ['svelte', '#material'],
}),
commonjs(),
postcss({
extract: 'css/app.css',
minimize: true,
sourceMap: true,
use: [
[
'sass', {
includePaths: [
'./theme',
'./node_modules',
],
},
],
],
}),
!production && serve(),
!production && livereload({watch: ['scripts', 'css', 'src', 'theme']}),
production && terser(),
],
watch: {
clearScreen: false,
},
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true,
});
}
},
};
}
It clearly tries to parse the scss file as css. So it probably misses the compile step. I can't find the scss rollup plugin in your package.json.
Check this, it could solve your problem: https://www.npmjs.com/package/rollup-plugin-scss

unexpected token import using karma with webpack and babel

I'm trying to run karma tests using karma, webpack and babel. I feel like I've configured properly but it seems that the test files are not being transpiled.
karma.conf:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
{pattern: 'src/**/*-test.js', watched: false}
],
exclude: [
],
preprocessors: {
'src/**/*-test.js': ['webpack']
},
webpack: require("./webpack.config.js"),
webpackMiddleware: {
stats: 'errors-only'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
webpack.config:
module.exports = {
entry: [
'react-hot-loader/patch',
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'src/index.js')
],
output: {
filename: 'bundle.js'
},
module: {
rules: [
{ test: /\.(js|jsx)$/, exclude: /(\/node_modules\/|test\.js$)/, use: 'babel-loader'},
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: 'url-loader?limit=100000' }
]
},
resolve: {
extensions: ['.js', '.jsx']
}
};
My test file uses import syntax to import expect from chai and runs a simple test taht expects true is equal true but when I run the karma I'm getting
uncaught syntaxerror: unexpected token import
I've had a look at similar question:
Karma + Webpack (babel-loader) + ES6 "Unexpected token import"
but no luck. I'm sure it's something simple in my configs. Has anyone seen similar?
this is a new project so using latest packages, webpack2 etc.
Any ideas greatly appreciated
C

How to get Browserify, Babel, and Coverage working together in Karma?

I'm growing weary of trying to get node libraries to work properly together, but it's part of the job, so here goes.
I have an ES6 application intended for a browser. I have a set of unit tests for my files that I'm bringing up from when my application was written in ES5. I use Browserify to handle importing/exporting modules and bundling my distro. This works fine when running the application in the browser. I can successfully Browserify the source and spec files and run the tests, and the tests pass. I'm very close to getting this working.
The only issue is the coverage. The closest I've come is showing coverage on the karma-browserify generated files, which each look like this:
require('/absolute/path/to/the/corresponding/file.js');
And the coverage obviously shows as 100% for all files, because each one is just one line.
This is my karma.conf.js:
import babelify from 'babelify';
import isparta from 'isparta';
import paths from './paths';
var normalizeBrowserName = (browser) => browser.toLowerCase().split(/[ /-]/)[0];
export default function(config) {
config.set({
basePath: '..',
browsers: ['PhantomJS'],
frameworks: ['browserify', 'jasmine'],
files: paths.test.files,
preprocessors: {
'app/**/*.js': ['browserify', 'sourcemap', 'coverage'],
[paths.test.testFiles]: ['babel'],
},
plugins: [
'karma-babel-preprocessor',
'karma-browserify',
'karma-coverage',
'karma-jasmine',
'karma-junit-reporter',
'karma-phantomjs-launcher',
'karma-sourcemap-loader',
],
autoWatch: false,
colors: false,
loggers: [{ type: 'console' }],
port: 9876,
reporters: ['progress', 'dots', 'junit', 'coverage'],
junitReporter: {
outputFile: paths.test.resultsOut,
suite: '',
},
browserify: {
debug: true,
noParse: paths.js.noparse(),
configure: (bundle) => {
bundle.once('prebundle', () => bundle.transform(babelify.configure({ ignore: 'lib/!**!/!*' })));
},
},
coverageReporter: {
instrumenters: { isparta },
instrumenter: {
[paths.test.cover]: 'isparta',
},
reporters: [
{ type: 'text', },
{ type: 'html', dir: paths.test.coverageOut, subdir: normalizeBrowserName },
{ type: 'cobertura', dir: paths.test.coverageOut, subdir: '.', file: 'coverage.xml' },
],
},
logLevel: config.LOG_DEBUG,
});
};
I really have no idea how any of these libraries work, so I don't know where to start in debugging this. I understand that the ordering of the preprocessors matters, so that Browserify runs on the source files, feeds the resulting link files into the source map generator, then the source map generator feeds the resulting whatever into karma-coverage. But there's some loss of communication between Browserify and whatever handles the coverage. Isparta (which uses istanbul behind the scenes) has no idea that browserify is running, and I don't know what it sees.
If anyone has any experience with testing modularized ES6 WITH proper code coverage, please let me know if I'm on the right track or if I should try something else.
This is the configuration that worked for me, note that I am using browserify-istanbul rather than isparata.
var istanbul = require('browserify-istanbul');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'mocha'],
files: [
'test/**/*Spec.js'
],
exclude: [
'**/*.sw?'
],
preprocessors: {
'test/**/*Spec.js': ['browserify', 'coverage']
},
browserify: {
debug: true,
transform: [
['babelify', {
ignore: /node_modules/
}],
istanbul({
ignore: ['test/**', '**/node_modules/**']
})
],
extensions: ['.jsx']
},
babelPreprocessor: {
options: {
sourceMap: 'inline'
},
sourceFileName: function(file) {
return file.originalPath;
}
},
coverageReporter: {
dir: 'coverage/',
reporters: [
{ type: 'text-summary' }
]
},
browserNoActivityTimeout: 180000,
reporters: ['coverage', 'progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
it was a massive pain to get working.
hope that helps
HOW TO: Karma + Babel + React + Browserify + Istanbul
I THINK I GOT IT.
If I don't, ping me gus+overflow#mythril.co
Not sure if the previous answer not working has to do with using jasmine instead of mocha but I got it working with these settings.
Required Packages: apart from the obvious (React, Karma, Jasmine, Browserify)
isparta - an Istanbul instrumenter for ES6
browserify-istanbul - a browserify transform
babelify - another browserify transform
babel - JS compiler
babel-preset-2015 - ES6 compile preset
babel-preset-react - React compile preset
Create a .babelrc file in your root dir.
I was very confused as to where to place babel options within the tools, but most (and these) babel tools will look for a .babelrc
{
"presets": ["es2015", "react"],
"sourceMap": "inline"
}
karma.config.js:
const isparta = require('isparta');
const istanbul = require('browserify-istanbul');
module.exports = function (config) {
config.set({
basePath: '',
browsers: ['Firefox', 'Chrome', 'PhantomJS', 'Safari'],
captureConsole: true,
clearContext: true,
colors: true,
files: [
// you need this for Phantom
'node_modules/phantomjs-polyfill/bind-polyfill.js',
// import any third party libs, we bundle them in another gulp task
'./build/libs/vendor-bundle.js',
// glob for spec files
'__PATH_TO_SPEC_FILES_/*.spec.js'
],
frameworks: ['jasmine', 'browserify'],
logLevel: config.LOG_INFO,
preprocessors: {
// I had to NOT include coverage, the browserify transform will handle it
'__PATH_TO_SPEC_FILES_/*.spec.js': 'browserify'
},
port: 9876,
reporters: ['progress', 'coverage'],
browserify: {
// we still use jQuery for some things :(
// I don't think most people will need this configure section
configure: function (bundle) {
bundle.on('prebundle', function () {
bundle.external(['jquery']);
});
},
transform: [
// this will transform your ES6 and/or JSX
['babelify'],
// (I think) returns files readable by the reporters
istanbul({
instrumenter: isparta, // <--module capable of reading babelified code
ignore: ['**/node_modules/**', '**/client-libs/**']
})
],
// our spec files use jsx and so .js will need to be compiled too
extensions: ['.js', '.jsx'],
// paths that we can `require()` from
paths: [
'./node_modules',
'./client-libs',
'./universal'
],
debug: true
},
coverageReporter: {
reporters: [
{ type: 'html', dir: 'coverage/Client' },
{ type: 'text-summary' }
]
}
});
};
With Karma, I think it would look something like this(?):
// Karma configuration
'use strict';
let babelify = require( 'babelify' );
let browserify = require('browserify');
let browserifyBabalIstanbul = require('browserify-babel-istanbul');
let isparta = require('isparta');
browserify: {
debug: true,
transform: [
browserifyBabalIstanbul({
instrumenter: isparta,
instrumenterConfig: { babel: { presets: ["es2015"] } },
ignore: ['**/node_modules/**', '**/unitest/**']
}),
[ babelify, { presets: ["es2015"] } ]
]
},
see the following link : Find a good way to get a coverage report with karma?

karma-browserify throws error when trying to load modules shimmed with browserify-shim

I know there were similar questions but none of them solved my problem.
When I run karma test it throws the following error, every time it tries to load a module, that was shimmed with browserify-shim:
TypeError: 'undefined' is not an object (evaluating 'module.exports = ex')
at /tmp/8ff1e03f7ba1f9c70ee4192510d267a2.browserify:3855:0 <- lib/underscore/underscore.js:1421:0
My karma.conf.js is the following:
module.exports = function(karma) {
karma.set({
frameworks: [ 'jasmine', 'browserify' ],
files: [
'test/spec/**/*Spec.js'
],
reporters: [ 'dots' ],
preprocessors: {
'test/spec/**/*Spec.js': [ 'browserify' ]
},
browsers: [ 'PhantomJS' ],
logLevel: 'LOG_DEBUG',
singleRun: true,
autoWatch: false,
// browserify configuration
browserify: {
debug: true,
transform: [ 'reactify', 'browserify-shim' ]
}
});
};
And here is the relevant part of my package.json file:
...
"browser": {
"underscore": "./lib/underscore/underscore.js",
"jquery": "./lib/jquery/dist/jquery.js",
"typeahead": "./lib/bootstrap3-typeahead/bootstrap3-typeahead.js",
"bootstrap": "./lib/bootstrap/dist/js/bootstrap.js",
"q": "./lib/q/q.js"
},
"browserify-shim": {
"underscore": "_",
"jquery": "jQuery",
"typeahead": {
"depends": [
"jquery"
]
}
},
"browserify": {
"transform": [
"browserify-shim"
]
},
....
Any idea what can caus the problem?
I had the same problem and have resolved it by removing the browserify-shim transform from karma configuration file, since it is already declared as a transform on package.json file.
Hope that helps.