Mocha tests don't run with Webpack and mocha-loader - npm

Background
I am porting some npm scripts to Webpack loaders to better learn how Webpack works and I’ve got everything working except for my Mocha tests: I have one failing test, but it is not showing that Mocha is being run with the mocha-loader or that the test is failing:
Question
What do I need to do differently to get all src/**/*.test.js files to run with with Mocha in Webpack?
Steps to reproduce
Clone https://github.com/trevordmiller/webpack-loaders-playground
Run npm test to see how tests should work
Run npm run dev to see how tests don't run with Webpack

Mocha loader won't run tests while building, it's used to create a bundle specifically containing your tests which you can then run from your browser.
I would recommend creating a separate webpack config file for your tests, which you can then host on a webpack-dev-server that uses a different port from your application. Here's an example that's more-or-less the pattern that I use for my own projects (as of writing this answer):
webpack.tests.config.js
module.exports = {
entry: 'mocha!./tests/index.js',
output: {
filename: 'test.build.js',
path: 'tests/',
publicPath: 'http://' + hostname + ':' + port + '/tests'
},
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel-loader']
},
{
test: /(\.css|\.less)$/,
loader: 'null-loader',
exclude: [
/build/
]
},
{
test: /(\.jpg|\.jpeg|\.png|\.gif)$/,
loader: 'null-loader'
}
]
},
devServer: {
host: hostname,
port: port
}
};
tests/index.js
// This will search for files ending in .test.js and require them
// so that they are added to the webpack bundle
var context = require.context('.', true, /.+\.test\.js?$/);
context.keys().forEach(context);
module.exports = context;
package.json
"scripts": {
"test": "find ./ -name '*.test.js' | xargs mocha -R min -r babel/register",
"devtest": "webpack-dev-server --config webpack.tests.config.js",
"dev": "webpack-dev-server --config webpack.config.js"
}
test.html
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./node_modules/mocha/mocha.css" />
<script src="/tests/test.build.js"></script>
</head>
<body>
</body>
</html>
Then run npm run devtest, open http://localhost:<port you picked>/webpack-dev-server/test.html, and mocha should run your tests.
If you don't require CSS/LESS or images through your modules, you can remove those loaders from webpack.tests.config.js.
With hot loading enabled this is a really great setup because I can have both my application and my tests running in different browser tabs, then update my code and see my changes and my tests re-running immediately.
You can also run npm run test to execute the same tests through the command line.
Hope this helps.

I liked JimSkerritt's answer, but couldn't get it to work on my computer for some reason. With the two config files below you can run the app via:
npm start // then http://localhost:8080/bundle
and run your tests with:
npm test // then http://localhost:8081/webpack-dev-server/test
both servers auto-reload && you can run both simultaneously!
Config Files
webpack.config.js
module.exports = {
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
}
};
package.json
{
"name": "2dpointfinder",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --inline",
"test": "webpack-dev-server 'mocha!./tests/test.js' --output-filename test.js --port 8081"
},
"author": "",
"license": "ISC",
"dependencies": {
"css-loader": "^0.19.0",
"style-loader": "^0.12.4"
},
"devDependencies": {
"mocha": "^2.3.3",
"mocha-loader": "^0.7.1",
"should": "^7.1.0"
}
}

Related

run webpack as a postinstall npm script

I'm updating a private node_module that we install in projects via bitbucket. The package has some overrides that get bundled up via webpack and that bundle is used directly (i.e. outside of the build tools used for the project I'm installing the module for).
I would like to fire the module's build command as a postinstall script so that when we install or update the module in the main project the bundle is rebuilt.
In the module's package.json I have this:
"scripts": {
"build": "webpack",
"dev": "webpack --watch",
"serve": "webpack-dev-server",
"postinstall": "npm run build"
},
and I have the following webpack.config.js file:
const path = require("path")
module.exports = {
mode: "development",
watch: false,
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
devServer: {
contentBase: "dist",
},
module: {
rules: [
{
test: /\.js/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
],
},
}
And I've confirmed that firing npm run build works just fine in the modules codebase, but when I go to update the module in the main codebase I get errors:
Webpack is blowing up on the option chaining which I thought would be handled by the babel loader in the module's webpack config.
I double checked my module's package.json file and it definitely has babel's presets in the regular dependencies and not the dev dependencies (i.e. it gets installed as part of the module install).
Am I doing something wrong here? It seems like if the same build process works
Make sure your exports in the package.json points to the sources in the dist:
"exports": {
".": "./dist/bundle.js"
},
https://nodejs.org/api/packages.html#package-entry-points

Webpack Error Reading/Resolving the Entry Module

I'm receiving an error when trying to execute a watch command on webpack and cannot figure out the problem. I have a feeling there's more than one issue, but I'm pretty sure I at least have an idea of one of the problems.
To give a little background, I'm way out of my know-how with all of this and am trying to self-teach how to write a web application with python. I stumbled onto this blog post with a basic example with detailed instructions:
https://codeburst.io/creating-a-full-stack-web-application-with-python-npm-webpack-and-react-8925800503d9
... and getting errors with no context from the source material. They also have a github and youtube video where it was presented, but still no such luck.
I think part of the issue is that their example was written on a MAC which the directory works a little different than windows which is my computer, so in part of the code the directory appears to be off because of that. Here's a screenshot showing the Node.js, the file folder, and the webpack.config.js code:
Here's a screenshot showing the Node.js, the file folder, and the webpack.config.js code:
I noticed that the directory in the example had had '/static/js/index.jsx', but my directory uses the other slash \static\js\index.jsx and the error shows the odd combining as C:\Users...\static/static/js/index.jsx. After learning that \ was an escape code in javascript, I eventually tried the code re-done with the changed slashes.
Here's another screenshot showing the newly run effect ... and it didn't appear to have an effect.
So I'm not sure if what I "fixed" was also an error, but not the current one since it doesn't make sense to me how directory slashes can change... but still no real answers and my knowledge on this was too thin to effectively look it up or learn the nature of the issue.
I have a feeling the actual module either is or may also have some kind of error in the webpack code, but I'm not too sure.
Thanks for any and all time on helping me out,
Matt
Edit: the original post had screenshots of the code and reference to the source material it was copied from, but for reference here are the code segments:
The directory layout is:
| Documents
|--- Python Scripts
|--- fullstacktemplate
|--- fullstack_template
|--- static
|--- js
|--- index.jsx
| node_modules
| index.html
| package.json
| package-lock.json
| webpack.config.js
The node_modules and package-lock.json were auto-created with set up of NPM, Webpack, and/or Babel. Package.json was further edited which will be listed below.
index.jsx is 1 line:
alert("Hello World!");
package.json is as follows:
{
"name": "fullstacktemplate",
"version": "1.0.0",
"description": "fullstack template that will say hello in another language when activated",
"main": "index.jsx",
"scripts": {
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --progress -d --config webpack.config.js --watch"
},
"keywords": [
"python",
"react",
"npm",
"webpack"
],
"author": "Matt Lane",
"license": "ISC",
"devDependencies": {
"webpack": "^4.28.2"
}
}
webpack.config.js is as follows:
const webpack = require('webpack');
const config = {
entry: __dirname + '\\js\\index.jsx',
output: {
path: __dirname + '\\dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;
The webpack.config.js file is my "corrected" one with the \ slashes. The original unedited version was:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;

How to build everything into a dist with folder structure by webpack?

I am a java developer for years and just new to the js world. This question sounds stupid but I don't know what's the proper/best way to build a dist for reactjs app for deploying to production(nginx/apache).
From my understanding, the dist just like simple web app and should looks like
contains:
index.html
client.js (bundled js after compiled)
static files, e.g.
images, css, js libraries, etc
I follow the guide on:
https://github.com/learncodeacademy/react-js-tutorials/tree/master/1-basic-react
and have a simple web app(maybe this is not called web app) running by:
npm run dev
it uses webpack to bundles the client.js.min and deploy to a embedded web server by node(maybe i am wrong).
Question:
How to build all the things by a command, say "npm run build" and it should built everything in a folder called "dist". So I can deploy it to web server root by copying every in dist to the web root.
package.json
{
"name": "react-tutorials",
"version": "0.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.0",
"babel-plugin-add-module-exports": "^0.1.2",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.3.13",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"react": "^0.14.6",
"react-dom": "^0.14.6",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.1"
},
"devDependencies": {},
"scripts": {
"dev": "webpack-dev-server --content-base src --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : false,
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
In your scripts dictionary of package.json add the following
"build" : "NODE_ENV='production' && node_modules/.bin/webpack -p"
This will tell webpack to read the config file and build it in production mode i.e minify etc etc. The -p flag does it. The node env is to ensure that production build are used for react and other libraries and to set an env variable of production for NODE_Env
To run type. npm run build

use different babel preset when running mocha tests

My npm package build runs with babel and I configured a babel preset in my package.json with
"babel": { "presets": ["es2015"] }
I also configured a mocha test script with
"test": "mocha --compilers js:babel-core/register"
However, I would like to run my tests using a different babel preset than that one specified for my build.
Is it possible? I would you achieve that?
Babel accommodates environment variables so you could set a test environment variable and alter your presets accordingly:
In your package.json:
"babel": {
"env": {
"test": {
"presets": [/* your test presets */]
}
},
"presets": [/* your usual presets */]
}
Then, run your mocha command like so:
"test: BABEL_ENV=test mocha --compilers js:babel-core/register"
You could create a file named babel-hook.js and put in it:
require("babel-register")({
presets: [ /* whatever values you want here */ ],
});
then run Mocha like this:
mocha --require babel-hook
This will register Babel and you can use any configuration option you want with it, separate from anything in package.json.
The answer about configuring babel in package.json was partially ok.
I needed to add seperate env entries to make it work cause otherwise the config outside env would always run.
So the final configuration example would look like this:
"babel": {
"env": {
"test-console": {
"presets": ["#babel/preset-env"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
,
"test": {
"presets": ["#babel/preset-env"],
"plugins": ["#babel/plugin-proposal-class-properties", "transform-remove-console"]
}
}
And scripts:
"scripts": {
"test-console-log": "BABEL_ENV=test-console mocha || TRUE",
"test": "BABEL_ENV=test mocha || TRUE"
}

Running Jest tests in Vue.js

Basically, the component isn't getting compiled, so I get an Unexpected token < error when it runs into <template>
I've run the following commands:
$ npm install --save-dev jest
$ npm install --save-dev vue-jest
$ npm install --save-dev vue-test-utils
and I've out the following in package.json:
"scripts": {
"dev": "node build/dev-server.js",
"build": "node build/build.js",
"test": "jest"
},
...
"jest": {
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/vue"
],
"moduleFileExtensions": [
"js",
"vue"
],
"scriptPreprocessor": "index.js"
}
I created a __test__ folder in the root directory with a simple test:
const Vue = require("vue");
const VueTestUtils = require("vue-test-utils");
Vue.config.debug = true;
Vue.config.async = false;
Vue.use(VueTestUtils.install);
import Hello from '../src/components/Hello.vue'
const Constructor = Vue.extend(Hello)
const vm = new Constructor().$mount()
describe('initial test', () => {
it('should be 1', () => {
expect(1).toBe(1)
})
})
I recently got this error as well, and not quite sure how to configure Vue.js so it will run using the compiler-included build:
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
Been looking around for a while, so any help would be appreciated
You need to use a Jest transform to transform Jest Vue files. A Jest transformer is a synchronous function, that takes the file and path as input and outputs transpiled code.
I maintain a npm package that does it for you - vue-jest.
npm install --save-dev vue-jest
You need to add a jest section to your package.json (or in a seperate file with --config). Your config should look something like this:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "babel-jest",
".*\\.(vue)$": "vue-jest"
}
}
This tells jest to use jest-vue as a transform for files with a .vue extension.
You can see a working repo using Vue Test Utils here - https://github.com/eddyerburgh/vue-test-utils-jest-example