I'm trying to run a simple test using react-testing-library, this under a react project without create-react-app (CRA) I have a basic webpack config and don't know if I need to setup anything else.
Here is the test
import React from "react";
import "#testing-library/jest-dom/extend-expect";
import { render } from "#testing-library/react";
import { prettyDOM } from "#testing-library/dom";
import Button from "./Button";
test("renders content", () => {
const props = {
text: "Test",
size: "lg",
color: "black",
type: "submit",
buttonClass: "button-oaauth-signup",
fullWidth: true,
};
const component = render(<Button {...props} />);
component.getByText("Test");
});
Here is my package.json
{
"name": "firmavirtual",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack --mode=development",
"build": "webpack --mode=production",
"dev": "webpack-dev-server",
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"#babel/preset-react": "^7.14.5",
"#svgr/webpack": "^5.5.0",
"#testing-library/jest-dom": "^5.15.0",
"#testing-library/react": "^12.1.2",
"babel-jest": "^27.3.1",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.0",
"file-loader": "^6.2.0",
"jest": "^27.3.1",
"node-sass": "^6.0.1",
"react-test-renderer": "^17.0.2",
"sass-loader": "^12.2.0",
"style-loader": "^3.3.1",
"svg-url-loader": "^7.1.1",
"webpack": "^5.60.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.3.1"
},
"dependencies": {
"#emotion/react": "^11.5.0",
"#emotion/styled": "^11.3.0",
"#mui/icons-material": "^5.0.5",
"#mui/material": "^5.0.6",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-google-login": "^5.2.2",
"react-hook-form": "^7.18.0",
"react-icons": "^4.3.1",
"react-router-dom": "^5.3.0"
}
}
Here is my webpack.config.js
const webpack = require("webpack");
const path = require("path");
module.exports = {
mode: "development",
entry: "./src/index.js",
resolve: {
extensions: [".js", ".json", ".jsx", ".scss", ".svg", ".png", ".jpg"],
modules: [path.resolve(__dirname, "src"), "node_modules"],
},
output: {
filename: "bundle.js",
path: path.join(__dirname, "public"),
},
plugins: [new webpack.HotModuleReplacementPlugin({})],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules|bower_components/,
loader: "babel-loader",
options: {
presets: ["#babel/env", "#babel/preset-react"],
},
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
{
test: /\.svg$/,
use: ["#svgr/webpack"],
},
{
test: /\.(woff(2)?|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "assets/fonts/",
},
},
],
},
],
},
devtool: "eval-cheap-module-source-map",
devServer: {
static: path.join(__dirname, "public"),
port: 5000,
},
};
Running npm run test show this error
> firmavirtual#1.0.0 test
> jest
FAIL src/components/buttons/Button.test.js
✕ renders content (2 ms)
● renders content
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
Consider using the "jsdom" test environment.
ReferenceError: document is not defined
15 | };
16 |
> 17 | const component = render(<Button {...props} />);
| ^
18 |
19 | component.getByText("Inicio con Google");
20 | });
at render (node_modules/#testing-library/react/dist/pure.js:83:5)
at Object.<anonymous> (src/components/buttons/Button.test.js:17:21)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 5.179 s
Ran all test suites.
Any idea how to fix this?
Well I guess I needed to search a little more
In jest.config.js add
module.exports = {
// Add the correct environment
testEnvironment: "jsdom",
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "identity-obj-proxy",
},
};
That solved the problem. Silly me
Related
I have a react project and I'm using Webpack (webpack-dev-server) for my development.
Everything compiles well, and when I make a change in my file (for the first time), the live reloading works well.
BUT, after changing the same file twice (or more), the live reloading stop working. In the console it says "nothing changed" even when I made a change.
Looks like the webpack-dev-server memory doesn't pick up the change. Any idea why?
Webpack Config
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ProvidePlugin } = require("webpack");
module.exports = {
target: "web",
mode: "development",
entry: ["regenerator-runtime/runtime.js", "./src/index.js"],
devtool: "inline-source-map",
devServer: {
historyApiFallback: true,
hot: true,
port: 8080,
static: "./dist",
watchFiles: "src/**/*,js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "index_bundle.js",
},
resolve: { extensions: ["*", ".js", ".jsx"] },
module: {
rules: [
{
test: /\.(jsx|js)$/,
exclude: /(node_modules)/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/env", "#babel/react"],
},
},
],
},
{
test: /\.css$/,
// exclude: /node_modules/,
use: ["style-loader", "css-loader"],
},
{
test: /\.svg$/,
use: [
{
loader: "svg-url-loader",
options: {
limit: 10000,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "src/index.html",
title: "Development",
}),
new ProvidePlugin({
React: "react",
}),
],
};
Package.json
{
"name": "timerfrontend",
"version": "1.0.0",
"main": "index.js",
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack serve",
"create": "webpack -w",
"build": "webpack -p"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.16.5",
"#babel/preset-env": "^7.16.5",
"#babel/preset-react": "^7.16.5",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"html-webpack-plugin": "^5.3.1",
"style-loader": "^3.3.1",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0"
},
"dependencies": {
"#apollo/client": "^3.5.6",
"#apollo/link-context": "^2.0.0-beta.3",
"#apollo/react-hooks": "^4.0.0",
"#auth0/auth0-react": "^1.8.0",
"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link-http": "^1.5.17",
"bootstrap": "^5.0.1",
"dayjs": "^1.10.5",
"npm-force-resolutions": "^0.0.10",
"prop-types": "^15.7.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.1.1",
"regenerator-runtime": "^0.13.9",
"svg-url-loader": "^7.1.1"
},
"description": "",
"resolutions": {
"react": "17.0.2",
"graphql": "16.1.0"
}
}
I found the solution (hint: its weird)
I realized that my Webpack live reloading was working on my other components (except the I had issue with).
I finally resolved to deleting that component and create a new one (exact copy) and then it worked perfectly!?
I still don't know why Webpack didn't like this component specifically...
It was happening to me, I checked the files and class names, they have to be exactly the same, including caps and lowercase letters
In my case, the file I was modified is not being use anywhere in project, so webpack does not recognize it.
After import and use it in the code, then it work fine
After a few hours of research, I still haven't solved an issue I've been having with Babel and Webpack. ): I'm sure the solution is simple.
My .babelrc:
{
"presets": ["#babel/preset-env", "#babel/preset-react", "#babel/preset-stage-0"]
}
My package.json
{
"name": "sabrinasbase",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"chokidar": "^3.5.1",
"css-modules-typescript-loader": "^4.0.1",
"next": "10.0.5",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-particles-js": "^3.4.1",
"react-tsparticles": "^1.18.11",
"sass": "^1.32.5",
"three": "^0.124.0"
},
"devDependencies": {
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"#babel/preset-stage-0": "^7.8.3",
"#babel/register": "^7.12.10",
"#types/node": "^14.14.22",
"#types/react": "^17.0.0",
"babel-loader": "^8.2.2",
"typescript": "^4.1.3",
"url-loader": "^4.1.1",
"webpack": "^5.16.0",
"webpack-cli": "^4.4.0",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.0.0"
},
"resolutions": {
"#babel/core": "^7.12.10"
}
}
My webpack.config.js
var path = require("path");
module.exports = {
//mode: "production",
mode: "development",
devtool: "inline-source-map",
context: path.join(__dirname, "pages"),
entry: ["/_app.js" /*main*/],
output: {
filename: "./bundle.js", // in /dist
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js", ".css", ".scss"],
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "ts-loader" },
{
test: /\.scss$/,
use: [
{ loader: "style-loader" }, // to inject the result into the DOM as a style block
{ loader: "css-modules-typescript-loader" }, // to generate a .d.ts module next to the .scss file (also requires a declaration.d.ts with "declare modules '*.scss';" in it to tell TypeScript that "import styles from './styles.scss';" means to load the module "./styles.scss.d.td")
{ loader: "css-loader", options: { modules: true } }, // to convert the resulting CSS to Javascript to be bundled (modules:true to rename CSS classes in output to cryptic identifiers, except if wrapped in a :global(...) pseudo class)
{ loader: "sass-loader" }, // to convert SASS to CSS
// NOTE: The first build after adding/removing/renaming CSS classes fails, since the newly generated .d.ts typescript module is picked up only later
],
},
{
test: /\.png|jpg|gif$/i,
use: [
{
loader: "url-loader",
options: {
limit: 8192,
},
},
],
},
{ test: /\.js|tsx|ts$/, loader: "babel-loader", exclude: /node_modules/ },
],
},
};
All I want to do is import a picture into a component. Originally I was getting Plugin/Preset files are not allowed to export objects, only functions error, but now I am getting vaguer errors that the module isn't working correctly. There were a few times that the Webpack would compile successfully, but the file I wanted to use wouldn't. Is there anything I am missing? I promise I am installing the preset-stage-0 package.
Error: Cannot find module '#babel/preset-stage-0'
Require stack:
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\compiled\babel\bundle.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\compiled\babel\code-frame.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\lib\typescript\diagnosticFormatter.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\lib\typescript\runTypeCheck.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\lib\verifyTypeScriptSetup.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\server\next-dev-server.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\server\next.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\server\lib\start-server.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\cli\next-dev.js
- C:\Users\Sabri\Documents\GitHub\sabrinasbase\sabrinasbase\node_modules\next\dist\bin\next
at Array.map (<anonymous>)
at Generator.next (<anonymous>)
at loadFileChain.next (<anonymous>)
Not sure why you are getting this error
Here is my webpack which works as expected
Also, apologies in advance as I have done heck load of optimization to reduce bundle size
Webpack.config.base.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
const CopyPlugin = require("copy-webpack-plugin");
const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin');
const {WebpackManifestPlugin} = require('webpack-manifest-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const PurifyCssPlugin = require('purifycss-webpack');
const glob = require("glob");
module.exports = {
target: 'web',
stats: 'verbose',
output: {
path: __dirname + '/dist',
filename: '[name].[hash].bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: './'
}
}, 'css-loader']
},
{
test: /\.scss$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: './'
}
}, 'css-loader', 'sass-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true, // webpack#1.x
disable: true, // webpack#2.x and newer
mozjpeg: {
progressive: true,
},
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false,
},
},
}
]
}
]
},
plugins: [
new CopyPlugin({
patterns: [
{from: "icons", to: "icons"},
{from: "./manifest.webmanifest", to: ""},
{from: "./.htaccess", to: ""},
{from: "./robots.txt", to: ""}
],
}),
new MiniCssExtractPlugin({
filename: "[name].[hash].css"
}),
new HtmlWebpackPlugin({
template: "./src/app/index.html",
favicon: "./src/assets/image/favicon.png",
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true
}
}),
new ServiceWorkerWebpackPlugin({
entry: path.join(__dirname, './src/app/serviceWorker/serviceWorkerInit.js'),
}),
new WebpackManifestPlugin({
fileName: 'asset-manifest.json', // Not to confuse with manifest.json
}),
new ESLintPlugin({files: './src/app/app.js'}),
new PurifyCssPlugin({
paths: [
...(glob.sync(`./src/app/*.html`)),
...(glob.sync(`./src/app/**/*.jsx`)),
...(glob.sync(`./dist/*.html`))
],
styleExtensions: ['.css','.scss'],
moduleExtensions: [".html"],
verbose: true,
purifyOptions: {
info: true,
minify: true,
whitelist: ["*purify*"]
},
})
]
};
Webpack.config.prod.js
const merge = require('webpack-merge');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const webpackBaseConfiguration = require('./webpack.config.base.js');
const TerserPlugin = require('terser-webpack-plugin')
const webpack = require('webpack');
const GLOBALS = {
'process.env.NODE_ENV': JSON.stringify('production'),
__DEV__: false
};
module.exports = merge(webpackBaseConfiguration,{
mode: 'production',
entry: [
'#babel/polyfill',
'./src/app/app.jsx'
],
devServer: {
contentBase: './dist'
},
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
maxSize: 0,
minChunks: 2,
maxAsyncRequests: 30,
maxInitialRequests: 30,
enforceSizeThreshold: 50000,
cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
usedExports: true,
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
ecma: 6,
},
}),
new OptimizeCSSAssetsPlugin()
]
},
plugins: [
new webpack.DefinePlugin(GLOBALS),
new CompressionPlugin({
algorithm: 'gzip',
minRatio: Number.MAX_SAFE_INTEGER
}),
new CompressionPlugin({
filename: "[path].br",
algorithm: "brotliCompress",
test: /\.(js|css|html|svg|png|svg|jpg|gif)$/,
deleteOriginalAssets: false,
minRatio: Number.MAX_SAFE_INTEGER
})
]
});
Webpack.config.dev.js
const merge = require('webpack-merge');
const webpackBaseConfiguration = require('./webpack.config.base');
const webpack = require('webpack');
module.exports = merge(webpackBaseConfiguration,{
mode: 'development',
output: {
publicPath: '/'
},
devServer: {
contentBase: './src',
historyApiFallback: true
},
devtool: 'cheap-module-eval-source-map',
entry: [
'#babel/polyfill',
'webpack-hot-middleware/client?reload=true',
'./src/app/app.jsx'
],
plugins: [
/*For hot deployment*/
new webpack.HotModuleReplacementPlugin()
]
});
package.json
{
"name": "Sample",
"version": "1.0.0",
"description": "React app",
"scripts": {
"clean": "rimraf dist",
"deploy": "node deploy",
"build:prod:deploy": "npm run clean && webpack --mode production --config webpack.config.prod.js && node deploy",
"build:prod": "npm run clean && webpack --mode production --config webpack.config.prod.js",
"build:dev": "webpack-dev-server --mode development --config webpack.config.dev.js --open --hot",
"start": "npm run build && npm run deploy",
"build": "npm run clean && webpack --mode production --config webpack.config.prod.js && npm run deploy"
},
"engines": {
"node": "14.x",
"npm": "6.x"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.12.1",
"#babel/core": "^7.2.2",
"#babel/node": "^7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/polyfill": "^7.2.5",
"#babel/preset-env": "^7.2.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"#gfx/zopfli": "^1.0.15",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.0.4",
"brotli-webpack-plugin": "^1.1.0",
"compression-webpack-plugin": "^2.0.0",
"copy-webpack-plugin": "6.2.1",
"css-loader": "^2.1.0",
"eslint": "^7.18.0",
"eslint-webpack-plugin": "^2.4.1",
"file-loader": "^3.0.1",
"ftp-deploy": "^2.4.0",
"glob": "^7.1.6",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"image-minimizer-webpack-plugin": "^1.0.0",
"image-webpack-loader": "^7.0.1",
"imagemin-gifsicle": "^7.0.0",
"imagemin-jpegtran": "^7.0.0",
"imagemin-optipng": "^8.0.0",
"imagemin-svgo": "^8.0.0",
"mini-css-extract-plugin": "^0.5.0",
"node-sass": "^4.14.1",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"purify-css": "^1.2.5",
"purifycss-webpack": "^0.7.0",
"rimraf": "^2.6.3",
"sass-loader": "^7.1.0",
"serviceworker-webpack-plugin": "^1.0.1",
"terser-webpack-plugin": "4.2.3",
"uglifyjs-webpack-plugin": "^2.1.1",
"webpack": "^4.40.0",
"webpack-cli": "^3.1.2",
"webpack-dev-middleware": "^3.5.2",
"webpack-dev-server": "^3.11.0",
"webpack-ftp-upload-plugin": "^1.0.3",
"webpack-hot-middleware": "^2.24.3",
"webpack-manifest-plugin": "^3.0.0",
"webpack-merge": "^4.2.1",
"workbox-cacheable-response": "^6.0.2",
"workbox-expiration": "^6.0.2",
"workbox-routing": "^6.0.2",
"workbox-strategies": "^6.0.2",
"workbox-webpack-plugin": "^6.0.2",
"zlib": "^1.0.5"
},
"dependencies": {
"axios": "^0.19.0",
"bootstrap": "^4.5.0",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"react-lazy-load-image-component": "^1.5.1",
"react-paginate": "^6.5.0",
"react-redux": "^7.2.2",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"redux": "^4.0.5",
"redux-immutable-state-invariant": "^2.1.0",
"redux-thunk": "^2.3.0"
}
}
I'm trying to Unit test my React component which imports another component that contains .png file. Because of this image, my test suits are failing to run.
I tried all the possible solutions with the below configuration, still no luck.
Please suggest, this is my project configuration.
This is my jest.config.json
{
"testRegex": "((\\.|/*.)(spec))\\.js?$"
}
My package.json
{
"name": "Application name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode development",
"test": "jest"
},
"jest": {
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
}
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.8.7",
"#babel/polyfill": "^7.10.1",
"#babel/preset-env": "^7.10.2",
"#babel/preset-react": "^7.8.3",
"axios-mock-adapter": "^1.18.1",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.0.6",
"css-loader": "^3.5.3",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-react": "^7.19.0",
"eslint-plugin-react-hooks": "^2.5.0",
"file-loader": "^6.0.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^26.0.1",
"prettier": "^2.0.5",
"react-hot-loader": "^4.12.19",
"redux-mock-store": "^1.5.4",
"style-loader": "^1.2.1",
"url-loader": "^4.1.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"#material-ui/core": "^4.10.2",
"#material-ui/icons": "^4.9.1",
"#material-ui/lab": "^4.0.0-alpha.56",
"axios": "^0.19.2",
"core-js": "^3.6.5",
"d3-sankey-diagram": "^0.7.3",
"husky": "^4.2.5",
"prop-types": "^15.7.2",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-google-charts": "^3.0.15",
"react-intl": "^4.6.3",
"react-redux": "^7.2.0",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-test-renderer": "^16.13.1",
"redux": "^4.0.5",
"redux-saga": "^1.1.3",
"regenerator-runtime": "^0.13.5"
}
}
My Webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: ['./src/index.js', '#babel/polyfill'],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.css$/i,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
{
test: /\.(jpe?g|gif|png|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
},
},
],
},
{
test: /\.(gif|png|jpe?g)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/images/',
},
},
],
},
],
// loaders: [{ test: /\.jsx?$/, loader: 'babel' }],
},
devServer: {
historyApiFallback: true,
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: './dist',
hot: true,
},
};
My .babelrc file
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Finally my test file:
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import MyPackage from '../Components/index';
Enzyme.configure({ adapter: new Adapter() });
describe('Some name', () => {
it('This should be loaded', () => {
const wrapper = shallow(<MyPackage />);
const x= wrapper.find('#selector').debug();
expect(x.prop('length')).toBe(1);
});
});
I tried adding mocks/fileMock.js with
export default '';
and mocks/styleMocks.js
module.exports = {};
still I see this error -
● Test suite failed to run
D:\ReactStuff\folder\myproject\src\assets\images\mylogo.png:1
�PNG
SyntaxError: Invalid or unexpected token
1 | import React from 'react';
> 2 | import { HeaderLogo} from '../assets/images/mylogo.png';
| ^
3 |
4 | const Header = () => {
5 | return (
What am I missing here. Please suggest
I'm having a different problem from the one here. babel-plugin-react-css-modules is not matching styles with styleName
I'm trying to search for the app class in my App.jsx file to confirm I've setup babel-plugin-react-css-modules with Enzyme. Unfortunately, I clearly haven't done so successfully, even though i seem to be following the supposed solution here: https://github.com/gajus/babel-plugin-react-css-modules/issues/168 (although I'm using Jest)
I'd really appreciate any help.
App.jsx
import React from 'react';
import { hot } from 'react-hot-loader/root';
import './App.css';
const App = () => (
<div styleName="App">
<h1>Hello World!</h1>
</div>
);
export default hot(App);
App.test.js
import {mount} from 'enzyme';
import React from 'react';
import App from './App';
it('has an App component which returns a div with the class named App', () => {
const wrapper = mount(<App />);
expect(wrapper.find('.app')).toHaveLength(1);
})
test failure message
Expected length: 1
Received length: 0
Received object: {}
I've confirmed that the issue is due to transpilation because the test passes when I search for the class App__App___1o-Fp which is what it appears as on localhost.
.babelrc
{
"env": {
"test": {
"presets": ["#babel/env", "#babel/preset-react"],
"plugins": [
[
"react-css-modules",
{
"generateScopedName": "[local]"
}]
]
}
},
"presets": ["#babel/env", "#babel/preset-react"],
"plugins": ["react-hot-loader/babel", [
"react-css-modules",
{
"generateScopedName": "[name]__[local]___[hash:base64:5]"
}
]
]
}
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.jsx",
mode: "development",
module: {
rules: [
{
enforce: "pre",
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "eslint-loader",
options: {
fix: true
}
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: ["babel-loader", "react-hot-loader/webpack"],
},
{
test: /\.css$/,
use: ["style-loader", {loader: "css-loader", options: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}}]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
},
resolve: {
alias: {
'react-dom': '#hot-loader/react-dom'
},
extensions: ["*", ".js", ".jsx"]
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
package.json
{
"name": "shopping-page",
"version": "1.0.0",
"description": "Hi!",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+ssh://git#gitlab.com/mgoldwater-nisum-com/shopping-page.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://gitlab.com/mgoldwater-nisum-com/shopping-page/issues"
},
"homepage": "https://gitlab.com/mgoldwater-nisum-com/shopping-page#README",
"dependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.3.1",
"#babel/preset-react": "^7.0.0",
"#hot-loader/react-dom": "^16.8.1",
"babel-jest": "^24.1.0",
"babel-loader": "^8.0.5",
"babel-plugin-react-css-modules": "^5.0.0",
"css-loader": "^2.1.0",
"enzyme": "^3.8.0",
"enzyme-adapter-react-16": "^1.9.1",
"eslint-loader": "^2.1.2",
"file-loader": "^3.0.1",
"identity-obj-proxy": "^3.0.0",
"jest": "^24.1.0",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"react-hot-loader": "^4.6.5",
"style-loader": "^0.23.1",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.1.14"
},
"devDependencies": {
"eslint": "^5.13.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.12.4"
},
"jest": {
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
"moduleNameMapper": {
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
}
}
}
Out of nowhere I started getting this error message,
Invalid configuration object. Webpack has been initialised using a
configuration object that does not match the API schema.
- configuration has an unknown property 'devserver'. These properties are valid: object { amd?, bail?, cache?, context?, dependencies?,
devServer?, devtool?, entry, externals?, loader?, module?, name?,
node?, output?, performance?, plugins?, profile?, recordsInputPath?,
recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?,
target?, watch?, watchOptions? } For typos: please correct them.
For loader options: webpack 2 no longer allows custom properties in
configuration.
Loaders should be updated to allow passing options via loader options in module.rules.
Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
plugins: [
new webpack.LoaderOptionsPlugin({
// test: /.xxx$/, // may apply this only for some modules
options: {
devserver: ...
}
})
]
I have been scouring the internet for the past 2 hours trying to find a solution but I am going round in circles!
Here is my .babelrc, webpack.config.js, .js and package.json files.
Any help would be amazing. Thanks
.babelrc
{
"presets":[
"react",
["es2015", {"modules": false, "loose": true}]
]
}
package.json
{
"name": "complete-intro-to-react",
"version": "1.0.0",
"description": "A two day workshop on a complete intro to React",
"main": "index.js",
"author": "Brian Holt <btholt#gmail.com>",
"license": "MIT",
"scripts": {
"test": "NODE_ENV=test jest",
"update-test": "npm run test -- -u",
"build": "webpack",
"dev": "webpack-dev-server",
"lint": "eslint js/**/*.js webpack.config.js",
"watch": "webpack --watch"
},
"dependencies": {
"axios": "0.15.2",
"express": "4.14.0",
"history": "^4.4.0",
"lodash": "4.16.2",
"preact": "^6.4.0",
"preact-compat": "^3.9.3",
"react": "15.3.2",
"react-dom": "15.3.2",
"react-redux": "4.4.0",
"react-router": "4.0.0-alpha.5",
"redux": "3.3.1",
"redux-thunk": "^2.1.0"
},
"devDependencies": {
"babel-core": "^6.16.0",
"babel-jest": "16.0.0",
"babel-loader": "^6.2.7",
"babel-plugin-transform-es2015-modules-commonjs": "^6.18.0",
"babel-polyfill": "^6.16.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2017": "6.16.0",
"babel-preset-react": "^6.16.0",
"babel-register": "6.16.0",
"css-loader": "0.25.0",
"enzyme": "2.0.0",
"enzyme-to-json": "^1.3.0",
"eslint": "3.6.1",
"eslint-config-standard": "6.1.0",
"eslint-config-standard-jsx": "3.1.0",
"eslint-config-standard-react": "4.1.0",
"eslint-loader": "1.3.0",
"eslint-plugin-promise": "2.0.1",
"eslint-plugin-react": "6.3.0",
"eslint-plugin-standard": "2.0.0",
"jest": "15.1.1",
"jsdom": "9.5.0",
"json-loader": "0.5.4",
"react-addons-test-utils": "15.3.2",
"react-test-renderer": "15.3.2",
"style-loader": "0.13.1",
"webpack": "^2.1.0-beta.22",
"webpack-dev-server": "1.16.2"
},
"directories": {
"test": "test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/btholt/complete-intro-to-react.git"
},
"keywords": [
"react",
"workshop",
"intro",
"redux"
],
"bugs": {
"url": "https://github.com/btholt/complete-intro-to-react/issues"
},
"homepage": "https://github.com/btholt/complete-intro-to-react#readme"
}
webpack.config.js
const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
devserver: {
publicPath: '/public/'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: false
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: true
}
}
]
}
]
}
}
and the .js file
import React from 'react'
import { render } from 'react-dom'
import '../public/normalize.css'
import '../public/style.css'
const App = React.createClass({
render () {
return (
<div className='app'>
<div className="landing">
<h1>svideo</h1>
<input type="text" placeholder='search' />
<a>or Browse All</a>
</div>
</div>
)
}
})
render(<App/>, document.getElementById('app'));
Capital "S" -->devServer not devserver!