karma config with browserify/babel - karma-jasmine

I have a karma conf that I try to make work with babel/browserify. It looks like this:
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
preprocessors: {
'../src/**/*.js': ['babel', 'browserify'],
'unit/*.spec.js': ['babel', 'browserify']
},
files: [
'../src/**/*.js',
'unit/*.spec.js'
],
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
}
});
};
Every time I run this configuration through gulp babel preprocessor returns the following error:
ERROR [preprocessor.babel]: Cannot read property 'bundleFile' of undefined

Try adding 'browserify' to 'frameworks', like this:
frameworks: ['browserify', 'jasmine']
I had the same error, fixed by doing this. Here's my working karma config
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
singleRun: true,
frameworks: ['browserify', 'mocha'],
reporters: ['dots'],
files: ['./*test.js'],
preprocessors: {
'*.js': ['browserify']
},
logLevel: 'LOG_DEBUG',
browserify: {
debug: true,
transform: [ ['babelify', {presets: ['es2015', "react"]} ] ]
}
});
};

The fixed config file:
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine', 'browserify'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
preprocessors: {
'../src/js/app.js': ['browserify'],
'../src/js/login/login-ctrl.js': ['browserify'],
'./unit/*.spec.js': ['browserify']
},
files: [
'../../node_modules/angular/angular.js',
'../../node_modules/angular-mocks/angular-mocks.js',
'../src/js/app.js',
'../dist/js/partials/templates-all.js',
'../src/js/login/login-ctrl.js',
'unit/*.spec.js'
],
browserify: {
debug: true,
transform: [
['babelify']
]
},
singleRun: false,
reporters: ['progress'],
colors: true
});
};

Related

How to exclude specific files from vue-cli-3 build?

Current configuration of project is:
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const UglifyJsPlugin = require("uglify-webpack-plugin");
module.exports = {
transpileDependencies: ["vuex-persist", "vuex-persistedstate"],
exclude: [
/w*worker.js\w*/g
],
configureWebpack: {
devtool: false,
optimization: {
splitChunks: {
minSize: 10000,
maxSize: 250000,
},
nodeEnv: "production",
minimize: true,
minimizer: [
new UglifyJsPlugin({
extractComments: 'false',
parallel: true,
}),
],
removeEmptyChunks: true,
removeAvailableModules: true,
mergeDuplicateChunks: true
},
plugins: [
new MonacoWebpackPlugin({
languages: ['javascript', 'css', 'html', 'typescript', 'json']
})
]
},
};
So, the problem was that vue parse the language worker files of the monaco-editor module. If I remove optimization options, in output I obtain the following not parsed files (worker.js)
But if I keep this optimization options, as a result, the following error occurs in the console
So the question is, how do I exclude this worker files from parsing?
Thank you in advance!

Vue SFC styles not being extracted in webpack production build

Trying to add vue (and SFCs) to my webpack app. The <template> and <script> blocks work fine, but for some reason the styles in the <style> block are not being extracted for production build.
In the dev build, it's extracting the .vue <style> block to a separate css file (named for the entrypoint). Which is OK but I'd prefer they went into my main stylesheet.
But no matter what I try, I can't get any .vue styles to show up (in any file) for the production build.
This is an abbreviated version of my webpack config:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
...
module.exports = (env) => {
return {
entry: {
app: ["./src/polyfills.js", "./src/scss/styles.scss", "./src/app.js"],
...
testview: "./src/js/views/TestView.js"
},
output: {
path: assets,
filename: "[name].[hash].js",
publicPath: "/static/"
},
resolve: {
modules: ["node_modules", "src"],
alias: {
vue$: "vue/dist/vue.esm.js"
},
extensions: ["*", ".js", ".vue"]
},
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader"
},
{
test: /\.js?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: [
[
"#babel/preset-env",
{
targets: {
browsers: ["> 1%", "last 2 versions", "ie >= 11"]
}
}
]
],
plugins: ["#babel/plugin-proposal-class-properties"],
code: true,
comments: true,
cacheDirectory: true,
babelrc: false
}
}
]
},
{
test: /\.s?[ac]ss$/,
use: [
"vue-style-loader",
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
sourceMap: ifNotProduction()
}
},
{
loader: "postcss-loader",
options: {
ident: "postcss",
sourceMap: ifNotProduction(),
plugins: () =>
ifProduction([
require("autoprefixer")({
preset: "default"
}),
require("cssnano"),
require("css-mqpacker")
])
}
},
{
loader: "sass-loader",
options: {
sourceMap: ifNotProduction()
}
}
]
}
]
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2,
minSize: 0
},
styles: {
name: "styles",
test: /\.css$/,
chunks: "all",
enforce: true
}
}
},
occurrenceOrder: true
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "style.[hash].css"
}),
new HtmlWebpackPlugin({
hash: true,
inject: false,
template: "./src/jinja-templates/base.html.j2",
filename: `${templates}/base.html.j2`,
})
]
};
};
The .vue file I'm using is this demo one. I'm trying to import it into the entrypoint called 'testview' which contains simply:
import Vue from "vue";
import MainContent from "../components/main-content";
let MainComponent = Vue.extend(MainContent);
new MainComponent().$mount("#mainContent");
Did figure it out. I had to remove sideEffects: false from my package.json. This issue explains it further.
Still would like to know how to extract the .vue styles to my main stylesheet As it is now, the .vue styles are extracting to a separate stylesheet (dev and production).

Vue-cli 3 how to integrate karma?

What problem does this feature solve?
karma Unit Testing
What does the proposed API look like?
Vue-cli 3 integration karma
Karma can't get the mode defined in vue-cli 3
Below is my karma.conf.js
const path = require('path')
const webpackConfig = require(path.join(process.cwd(), '/node_modules/#vue/cli-service/webpack.config.js'))
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
'test/*.test.js'
],
exclude: [
'node_modules'
],
preprocessors: {
'test/*.test.js': ['webpack', 'sourcemap']
},
webpack: {
...webpackConfig,
mode: 'production'
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}

karma+webpack+typescript+mocha require is not defined

I try to configure my environment to run tests on node.
This my my webpack.config.test.js
const serverConfig = {
module: {
loaders: [
{test: /\.tsx?$/, loader: 'ts-loader' }
]
},
target: 'node',
externals:[nodeExternals()],
resolve: {
extensions: ['.ts', '.tsx', '.js']
}
};
module.exports = serverConfig;
karma.config.js
// Karma configuration
// Generated on Tue Jun 27 2017 07:20:43 GMT-0500 (Hora est. Pacífico, Sudamérica)
const webpackConfig=require('./config/webpack/webpack.test');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha','es6-shim'],
plugins:[
require("karma-es6-shim"),
'karma-webpack',
'karma-jsdom-launcher',
'karma-mocha',
'karma-spec-reporter',
'karma-jsdom-launcher',
'karma-coverage',
'karma-chrome-launcher',
"karma-phantomjs-launcher",
'karma-htmlfile-reporter'
],
files: [
'test/**/*.spec.ts'
],
coverageReporter: {
webpackMiddleware: {
stats: "errors-only"
},
dir: 'build/coverage/',
reporters: [
{ type: 'html' },
{ type: 'text' },
{ type: 'text-summary' }
]
},
// list of files to exclude
exclude: [
],
preprocessors: {
'test/**/*.spec.ts':["webpack","coverage"]
},
webpack:webpackConfig,
reporters: ['spec','progress','html'],
htmlReporter: {
outputFile: 'tests/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// web server port
port: 9876,
colors: true,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
}
test1
import { DBCONFIG } from './../src/config/db.config';
import { CONEXION } from './../src/config/database/mongo';
import { expect } from 'chai';
describe("#DATABASE",()=>{
it("Esta conectado",()=>{
CONEXION("hola",DBCONFIG.MONGO_URL_LOCAL)
.then(()=>{
expect(1).to.be("1");
})
.catch((e)=>{
expect(1).to.be(e);
})
})
});
test2
import { expect } from 'chai';
describe("#User",()=>{
it("use2r",()=>{
expect(1).to.equal("1");
})
})
When I run mocha + webpack with mocha-webpack, there is no problem the tests are running.
package.json
"test-server": "mocha-webpack --timeout 1000 --webpack-config config/webpack/webpack.test.js test/**/*.spec.ts",
"test":"karma start"
When I do it from karma depending on which browser I use to display the messages I throw similar errors, when I throw it with jsdom or PhantomJS I throw the following
require is not defined o Cannot find
Looking in git, the only answer that solved the problem, is to put in the processors of karma the following.
'test/**/*.spec.ts':["webpack","coverage"]
It is the same way and I have varied, but the error continues.

Syntax error when testing React component Jasmine and Webpack

I keep getting an error when trying to run a simple test using React, Karma, Jasmine and Webpack. The error is ' Uncaught SyntaxError: Unexpected token < ', I think my jsx isn't being processed to js, but I don't know why that is happening as I understand webpack should handle that using the babel loader. If anyone can provide advice I would be grateful
Here are my files
karma.conf.js
var webpack = require("webpack"),
path = require("path");
// Karma configuration
module.exports = function(config) {
config.set({
basePath: "",
frameworks: ["jasmine"],
files: [
"../test/!**!/!*.test.js"
],
preprocessors: {
"./test/!**!/!*.test.js": ["webpack"]
},
webpack: {
module: {
loaders: [
{
test: /\.jsx?$/i,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{ test: /\.less$/, loader: "style!css!less" }
]
},
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
])
],
resolve: {
root: __dirname,
extensions: [
'',
'.json',
'.js',
'.jsx'
]
}
},
webpackMiddleware: {
noInfo: true
},
plugins: [
require("karma-webpack"),
require("karma-jasmine"),
require("karma-chrome-launcher")
],
reporters: ["dots"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false
});
};
my test file example.test.js
var Comp = require('../../../js/common/components/MyComp.jsx'),
React = require('react'),
TestUtils = React.addons.TestUtils;
describe("Component Test", function() {
it("renders an h1", function () {
var component = TestUtils.renderIntoDocument(
<Comp/> // syntax error here
);
var h2 = TestUtils.findRenderedDOMComponentWithTag(
component, 'h2'
);
expect(h1).toExist();
});
});
So the syntax error happens at < Comp... . Thanks!
Apologise it was an error in setting the correct path to the test file.
files: [
"../test/**/*.test.js"
],
preprocessors: {
"../test/**/*.test.js": ["webpack"]
},