karma+webpack+typescript+mocha require is not defined - phantomjs

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.

Related

Webpack is throwing lots of errors from node modules when running watch-development

When running watch-development I am plagued with so many errors from my node modules and I'm not sure where to begin to even resolve some of them. Maybe something is wrong with my webpack configuration but I have tried looking for a solution for days now and have found nothing
Some of the errors:
TS2307: Cannot find module 'rxjs-compat/operators/multicast'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\observeOn.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\observeOn.ts(1,15)
TS2307: Cannot find module 'rxjs-compat/operators/observeOn'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\onErrorResumeNext.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\onErrorResumeNext.ts(1,15)
TS2307: Cannot find module 'rxjs-compat/operators/onErrorResumeNext'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\pairwise.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\rxjs\src\operators\pairwise.ts(1,15)
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(37,3)
TS2552: Cannot find name 'expect'. Did you mean 'expected'?
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(40,1)
TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i #types/jest` or `npm i #types/mocha`.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(42,3)
TS2304: Cannot find name 'expect'.
ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts
[tsl] ERROR in D:\Projects\Hospitality\content\Hospitality\node_modules\vue-functional-data-merge\__test__\array-merge.test.ts(45,3)
I have hundreds of errors like this all coming from my node modules, Mostly complaining it can't find a module, but also some complaining it cannot find name 'x'
this is my webpack config:
/// <binding />
"use strict";
module.exports = (env, options) => {
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoader = require("vue-loader");
let pathsToClean = ['dist/*.*', 'dist/fonts/*.*', 'dist/images/*.*'];
let cleanOptions = {
root: __dirname + '/wwwroot/',
verbose: true,
dry: false
};
return {
mode: 'development',
entry: {
app: './wwwroot/VueApp/Home/app.ts',
mainCss: './wwwroot/VueApp/CSS/site.scss'
},
devtool: 'source-map',
plugins: [
new CleanWebpackPlugin(pathsToClean, cleanOptions),
new webpack.ProvidePlugin({
Popper: ['popper.js', 'default'],
moment: 'moment',
vueResource: 'vue-resource',
vueRouter: 'vue-router',
vuex: 'vuex'
}),
new VueLoader.VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "[name].bundle.css"
})
],
output: {
publicPath: "/dist/",
path: path.join(__dirname, '/wwwroot/dist/'),
filename: '[name].bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
query: {
presets: [
['env', { targets: { uglify: true } }]
]
}
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { minimize: true, sourceMap: false } },
{
loader: 'sass-loader', options: { sourceMap: false } }
],
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 8 * 1024,
name: './images/[name].[ext]'
}
}
},
{
test: /\.(eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 8 * 1024,
name: './fonts/[name].[ext]'
}
}
},
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
resolve: {
alias: {
vue: 'vue/dist/vue.js'
},
extensions: ['.ts', '.js', '.vue', '.json']
}
};
};
this is what my file structure looks like:
https://ibb.co/xjQMCX0

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).

Cannot Find Children When Using Enzyme JS Mount

My expectation is that when I use Enzyme's mount function, I should be able to not only query for nodes in the top level element, but also nodes/elements that are rendered in child components.
Here are the tests exhibited in the matter:
import React from 'react';
import chai from 'chai'
import chaiEnzyme from 'chai-enzyme'
chai.use(chaiEnzyme());
const expect = chai.expect;
import {
shallow,
mount
} from 'enzyme';
class Child extends React.Component {
render() {
return <div id='child'>
CHILD
<button onClick={() => console.log('hit me')}>HIT ME</button>
</div>
}
}
class Parent extends React.Component {
render() {
return <div id='root'>
<Child aprop={1}/>
</div>
}
}
describe('example', function() {
describe('mounted', function() {
it('should find the button', function() {
const wrapper = mount(<Parent/>);
expect(wrapper.find('button').length).to.equal(1);
});
it('should find Child component', function() {
const wrapper = mount(<Parent/>);
console.log(wrapper.debug());
expect(wrapper.find(Child).length).to.equal(1);
});
});
describe('shallow', function() {
it('should not find the button', function() {
const wrapper = shallow(<Parent/>);
expect(wrapper.find('button').length).to.equal(0);
});
it('should find Child component', function() {
const wrapper = shallow(<Parent/>);
expect(wrapper.find(Child).length).to.equal(1);
});
});
});
The output is:
example
mounted
✗ should find the button
expected 0 to equal 1
AssertionError#webpack:///~/assertion-error/index.js?6193**:74:0 <- test/components/mount.spec.js:373:25
assert#webpack:///~/chai/lib/chai/assertion.js?fee1**:107:0 <- test/components/mount.spec.js:4705:32
assertEqual#webpack:///~/chai/lib/chai/core/assertions.js?b343**:487:0 <- test/components/mount.spec.js:5222:19
webpack:///~/chai/lib/chai/utils/addMethod.js?ca90**:41:0 <- test/components/mount.spec.js:4292:31
webpack:///test/components/mount.spec.js:35:53 <- test/components/mount.spec.js:153:54
LOG LOG: '<Parent />'
✗ should find Child component
expected 0 to equal 1
AssertionError#webpack:///~/assertion-error/index.js?6193**:74:0 <- test/components/mount.spec.js:373:25
assert#webpack:///~/chai/lib/chai/assertion.js?fee1**:107:0 <- test/components/mount.spec.js:4705:32
assertEqual#webpack:///~/chai/lib/chai/core/assertions.js?b343**:487:0 <- test/components/mount.spec.js:5222:19
webpack:///~/chai/lib/chai/utils/addMethod.js?ca90**:41:0 <- test/components/mount.spec.js:4292:31
webpack:///test/components/mount.spec.js:41:50 <- test/components/mount.spec.js:159:51
shallow
✓ should not find the button
✓ should find Child component
Either mount is not working as expected, or my understanding isn't correct.
Here is my Karma/Webpack file if it helps:
const webpack = require('webpack');
var argv = require('yargs').argv;
var path = require('path');
let srcPath = path.join(__dirname, '/../src/');
const webpackConfig = {
devtool: 'inline-source-map',
resolve: {
// allow us to import components in tests like:
// import Example from 'components/Example';
root: path.resolve(__dirname, './src'),
// allow us to avoid including extension name
extensions: ['', '.js', '.jsx', '.css', '.scss', '.json'],
// required for enzyme to work properly
alias: {
'sinon': 'sinon/pkg/sinon',
}
},
module: {
// don't run babel-loader through the sinon module
noParse: [
/node_modules\/sinon\//
],
isparta: {
embedSource: true,
noAutoWrap: true,
// these babel options will be passed only to isparta and not to babel-loader
babel: {
presets: ['es2015', 'stage-0', 'react']
}
},
// run babel loader for our tests
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
exclude: path.resolve(__dirname, 'node_modules'),
query: {
plugins: ['transform-decorators-legacy'],
presets: ['es2015', 'airbnb', 'stage-1', 'react']
}
},
{
test: /\.json$/, loader: 'json'
},
{
test: /\.scss$/,
exclude: /[\/\\](node_modules|bower_components|public)[\/\\]/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[local]',
'postcss',
'sass'
]
},
{
test: /\.css$/,
exclude: /[\/\\](node_modules|bower_components|public)[\/\\]/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[local]'
]
}
],
preLoaders: [ { //delays coverage til after tests are run, fixing transpiled source coverage error
test: /\.(jsx|js)$/,
include: path.resolve('src/'),
loader: 'isparta',
} ]
},
plugins: [
new webpack.IgnorePlugin(/node-fetch/)
],
// required for enzyme to work properly
externals: {
'jsdom': 'window',
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': 'window',
'react/addons': true
},
};
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
singleRun: !argv.watch,
frameworks: ['mocha', 'chai'],
reporters: ['spec', 'coverage'],
// include some polyfills for babel and phantomjs
files: [
'node_modules/whatwg-fetch/fetch.js',
'node_modules/babel-polyfill/dist/polyfill.js',
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'test/**/*.js'
],
preprocessors: {
// add webpack as preprocessor
'src/**/*.js': ['webpack', 'sourcemap'],
'test/**/*.js': ['webpack', 'sourcemap']
},
// A lot of people will reuse the same webpack config that they use
// in development for karma but remove any production plugins like UglifyJS etc.
// I chose to just re-write the config so readers can see what it needs to have
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: 'coverage/',
reporters: [
{ type: 'html' },
{ type: 'text' }
]
},
// tell karma all the plugins we're going to be using to prevent warnings
plugins: [
'karma-mocha',
'karma-chai',
'karma-webpack',
'karma-phantomjs-launcher',
'karma-spec-reporter',
'karma-sourcemap-loader',
'karma-coverage'
]
});
};

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"]
},

karma config with browserify/babel

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
});
};