Jest Coverage shows me code coverage report already compiled - reactjs

I'm using React and when I run the unit tests with "jest --coverage", the coverage report shows me the already compiled code (attached image).
It should show me in the report the component as I wrote it (I attach the code of my component).
Here the versions of the dependencies:
react: "17.0.2",
react-dom: "17.0.2",
#babel/preset-env: "^7.16.11",
#babel/preset-react: "^7.16.7",
#types/jest: "^27.4.1",
babel-jest: "^27.5.1",
babel-preset-env: "^1.7.0",
jest: "^27.5.1",
jest-canvas-mock: "^2.3.1",
jest-junit: "^13.0.0",
jest-next-dynamic: "^1.0.1",
ts-jest: "^27.1.3"
This is my code.
import React from 'react';
import Logo from '#Icons/Logo.svg';
import styles from '#Pages/Modules/Public/index.module.scss';
export default function SecondPage() {
return (
<div className={`${styles.p_landing_info}`}>
<div className={`${styles.p_landing_info__body} e-container`}>
<div className={styles.p_landing_info__observation_footer}>
<p className='e-p3 e-text-medium'>
A tu lado todo el camino
</p>
<Logo className={styles.p_landing_info__footer_logo} />
</div>
</div>
</div>
);
}
This is my jest.config.js
module.exports = {
moduleFileExtensions: [
'ts',
'tsx',
'js'
],
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testMatch: [
'**/*.(test|spec).(ts|tsx)'
],
testEnvironment: 'jsdom',
globals: {
'ts-jest': {
babelConfig: true,
tsconfig: 'jest.tsconfig.json'
}
},
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'pages/**/*.{js,jsx,ts,tsx}',
'!pages/**/_*.{js,jsx,ts,tsx}',
],
coveragePathIgnorePatterns: [
'/node_modules/',
'enzyme.js',
],
setupFilesAfterEnv: ['<rootDir>/enzyme.js', 'jest-canvas-mock', '<rootDir>/jest.env.ts'],
coverageReporters: [
'json',
'lcov',
'text',
'text-summary'
],
reporters: [
'default',
['jest-junit', {
'suiteName': 'jest tests',
'outputDirectory': 'coverage',
'outputName': 'junit.xml',
'classNameTemplate': '{classname} - {title}',
'titleTemplate': '{classname} - {title}',
'ancestorSeparator': ' > ',
'usePathForSuiteName': 'true'
}]
],
testResultsProcessor: 'jest-junit',
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|scss)$': 'identity-obj-proxy',
'#Src/(.*)': '<rootDir>/src/$1',
'#Pages/(.*)': '<rootDir>/pages/$1',
'#Icons/(.*)': '<rootDir>/src/Icons/$1',
}
};
This is Result Report of Jest.
Image Report
Thanks in advance.

I found the solution, it was just in the file jest.tsconfig.json change the field "sourceMap" to true:
{
"compilerOptions": {
{...},
"sourceMap": true,
}
}

Related

ReactJs: Jest failed to parse a file

I'm using react with typecript and after adding swiper dependecy my tests start to fail.
These are my configuration:
jest.config.js:
import type { Config } from '#jest/types';
const config: Config.InitialOptions = {
verbose: true,
transform: {
'^.+\\.ts?$': 'ts-jest',
},
transformIgnorePatterns: ['node_modules/(?!swiper|ssr-window|dom7/)'],
};
export default config;
babel.config.js:
module.exports = {
presets: ['#babel/preset-env', '#babel/preset-react', '#babel/preset-flow'],
plugins: [
'babel-plugin-styled-components',
'#babel/plugin-proposal-class-properties',
],
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)$': '<rootDir>/__mocks__/styleMock.js',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
},
transform: {
'^.+\\.ts?$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest',
},
};
package.json:
"jest": {
"moduleNameMapper": {
"swiper/react": "swiper/react/swiper-react.js",
"swiper/css": "swiper/swiper.min.css"
},
"transform": {
"^.+\\.css$": "jest-transform-css"
}
},
"transformIgnorePatterns": "node_modules/(?!(swiper|ssr-window|dom7)/)",
After doing lots of research and applying them, the only solution i found was to downgrade to v6
I actually had the same issue with swiper and these lines in jest.config.js solved it:
transformIgnorePatterns: ['/node_modules/(?!swiper|ssr-window|dom7)'],
moduleNameMapper: {
'swiper/react': ['<rootDir>/node_modules/swiper/react/swiper-react.js'],
},

Jest: Fail upon parsing a file

I'm using react with typecript and after adding swiper dependecy my tests start to fail.
These are my configuration:
jest.config.ts:
import type { Config } from '#jest/types';
const config: Config.InitialOptions = {
verbose: true,
transform: {
'^.+\\.ts?$': 'ts-jest',
},
transformIgnorePatterns: ['node_modules/(?!swiper|ssr-window|dom7/)'],
};
export default config;
babel.config.js
module.exports = {
presets: ['#babel/preset-env', '#babel/preset-react', '#babel/preset-flow'],
plugins: [
'babel-plugin-styled-components',
'#babel/plugin-proposal-class-properties',
],
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)$': '<rootDir>/__mocks__/styleMock.js',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
},
transform: {
'^.+\\.ts?$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest',
},
};
package.json
...
"jest": {
"moduleNameMapper": {
"swiper/react": "swiper/react/swiper-react.js",
"swiper/css": "swiper/swiper.min.css"
},
"transform": {
"^.+\\.css$": "jest-transform-css"
}
},
"transformIgnorePatterns": "node_modules/(?!(swiper|ssr-window|dom7)/)",
...

Jest cannot parse error with Jest + Enzyme testing in reactjs

I am facing issue with jest testing..
Basically I have made configuration with following steps:
script in package.json:
"jest": {
"scriptPreprocessor": "<rootDir>/jest-script-preprocessor",
"moduleFileExtensions": [
"js",
"json",
"jsx"
],
"moduleNameMapper": {
"^.*[.](jpg|JPG|gif|GIF|png|PNG|less|LESS|css|CSS)$": "EmptyModule"
},
"preprocessorIgnorePatterns": [
"/node_modules/"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/EmptyModule.js"
]
},
"peerDependencies": {
"babel-core": "6.x | ^7.0.0-0"
}
And in jest-script-preprocessor.js
import babelJest from 'babel-jest'
module.exports = {
process: (src, filename) => {
return babelJest.process(src, filename)
.replace(/^require.*\.less.*;$/gm, '')
}
}
Let me know valuable way to get it resolve.

transpiled code (babel) seems not working in Browser

Hi I'm working on an existing app which needs enhancements. The app is built using angularJS, Babel, webpack. I struggled running the app locally and finally succeeded in running it after making changes to how we call a basedirective (like below) which was using babel next generation javascript notation to regular notation (a compiler is present on babel site to do this).
function filtersDirective() {
return {
...baseDirective(template, FiltersCtrl),
...{
bindToController: {
customers: '=',
regions: '=',
managers: '=',
projects: '=',
statuses: '=',
},
},
}
}
Now the issue is I'm able to run this app locally and also able to build the bundle files (app.bundle.js, vendor.bundle.js, manifest.bundle.js) but when I deploy these files to my test server, the console error is like below.
ReferenceError: production is not defined
at dispatchXhrRequest (vendor.bundle.js:24340)
at new Promise (<anonymous>)
at xhrAdapter (vendor.bundle.js:24325)
at dispatchRequest (vendor.bundle.js:92054)
at <anonymous>
vendor.bundle.js:65932
TypeError: Cannot read property 'map' of undefined
at https://#domain/cdn/3.2.1/vendor.bundle.js:5202:31
at https://#domain/cdn/3.2.1/vendor.bundle.js:5090:28
at f1 (https://#domain/cdn/3.2.1/vendor.bundle.js:5070:27)
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4672:27
at getAttributeFromProjects (https://#domain/cdn/3.2.1/app.bundle.js:117:10)
at MainController (https://#domain/cdn/3.2.1/app.bundle.js:127:21)
at invoke (https://#domain/cdn/3.2.1/vendor.bundle.js:58052:17) <div ui-view="" class="ng-scope">
My Traspiled app.bundle.js looks like below
webpackJsonp([1], {
/***/
101:
/***/
(function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_deepmerge__ = __webpack_require__(69);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_deepmerge___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_deepmerge__);
const baseConfig = {
title: 'Test Dashboard',
dashboard: {
title: 'Test Report',
subtitle: 'Weekly Highlights'
},
header: {
title: 'Company Confidential',
nav: 'Test'
}
}
let config = baseConfig
if (window.AppConfig) {
if (window.AppConfig.config) {
config = __WEBPACK_IMPORTED_MODULE_0_deepmerge___default.a(baseConfig, window.AppConfig.config)
}
}
const {
title,
dashboard,
header,
statusBar
} = config
/* harmony export (immutable) */
__webpack_exports__["c"] = title;
/* harmony export (immutable) */
__webpack_exports__["a"] = dashboard;
/* unused harmony export header */
/* unused harmony export statusBar */
/* harmony default export */
__webpack_exports__["b"] = (config);
/***/
}),
/***/
222:
/***/
(function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */
__webpack_require__.d(__webpack_exports__, "b", function() {
return resolve;
});
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_ramda__ = __webpack_require__(36);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_ramda___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_ramda__);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_1_angular__ = __webpack_require__(7);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_1_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_angular__);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_2__utils__ = __webpack_require__(4);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_3__services_api__ = __webpack_require__(99);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_4__appConfig_config__ = __webpack_require__(101);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_5__dashboard_html__ = __webpack_require__(479);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__dashboard_html__);
/* harmony reexport (default from non-hamory) */
__webpack_require__.d(__webpack_exports__, "c", function() {
return __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default.a;
});
Which is very different from previous version of app.bundle.js which is on prod server which looks like below
webpackJsonp([1], {
/***/
10:
/***/
(function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getWebpartData = undefined;
var _keys = __webpack_require__(124);
var _keys2 = _interopRequireDefault(_keys);
var _deepmerge = __webpack_require__(76);
var _deepmerge2 = _interopRequireDefault(_deepmerge);
var _utils = __webpack_require__(4);
var _majorMilestones = __webpack_require__(501);
var _majorMilestones2 = _interopRequireDefault(_majorMilestones);
var _budget = __webpack_require__(502);
var _budget2 = _interopRequireDefault(_budget);
var _projectRisksAndIssues = __webpack_require__(503);
var _projectRisksAndIssues2 = _interopRequireDefault(_projectRisksAndIssues);
var _actionItems = __webpack_require__(504);
var _actionItems2 = _interopRequireDefault(_actionItems);
var _keyDates = __webpack_require__(505);
var _keyDates2 = _interopRequireDefault(_keyDates);
var _gantt = __webpack_require__(506);
var _gantt2 = _interopRequireDefault(_gantt);
var _statusBar = __webpack_require__(507);
var _statusBar2 = _interopRequireDefault(_statusBar);
var _angular = __webpack_require__(6);
var _angular2 = _interopRequireDefault(_angular);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
below is my package.json file for reference
{
"name": "pmrdashboard",
"version": "3.2.1",
"dependencies": {
"#cgross/angular-notify": "2.5.1",
"angular": "1.4.2",
"angular-bootstrap": "~0.12.2",
"angular-chart.js": "^1.0.1",
"angular-gantt": "^1.2.13",
"angular-google-chart": "^0.1.0",
"angular-messages": "~1.4.2",
"angular-moment": "1.0.1",
"angular-pubsub": "^0.2.0",
"angular-resource": "~1.4.2",
"angular-sanitize": "~1.4.2",
"angular-strap": "^2.3.9",
"angular-toastr": "~1.5.0",
"angular-ui-router": "~0.2.15",
"animate.css": "~3.4.0",
"axios": "^0.16.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-polyfill": "^6.23.0",
"babel-runtime": "^6.23.0",
"bootstrap-sass": "3.3.7",
"chart.js": "2.1.0",
"deepmerge": "^1.3.2",
"echo-loader": "0.0.1",
"jquery": "~2.1.4",
"lodash": "^4.13.1",
"moment": "2.10.6",
"ngsticky-puemos": "^0.0.4",
"node-sass": "4.5.3",
"ramda": "^0.22.1"
},
"scripts": {
"dev": "babel-node scripts/cli.js dev",
"serve": "babel-node scripts/cli.js serve",
"build": "babel-node scripts/cli.js build --upload=false --plugins dynamic-import-node",
"deploy": "babel-node scripts/cli.js build",
"serve:prod": "babel-node scripts/cli.js serve:prod",
"serve:optimize": "babel-node scripts/cli.js serve:prod --optimize=true",
"serve:cdn": "babel-node scripts/cli.js serve:prod --usecdn=true"
},
"devDependencies": {
"babel-eslint": "^7.2.3",
"babel-loader": "^7.0.0",
"babel-plugin-angularjs-annotate": "^0.7.0",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.5.1",
"chalk": "^1.1.3",
"clean-webpack-plugin": "0.1.16",
"cross-env": "^5.1.3",
"css-loader": "0.28.1",
"eslint": "2.13.1",
"eslint-config-angular": "^0.5.0",
"eslint-plugin-angular": "^2.4.0",
"execa": "^0.6.3",
"exports-loader": "0.6.4",
"express": "^4.15.3",
"extract-text-webpack-plugin": "2.1.0",
"file-loader": "0.11.1",
"fs-extra": "^3.0.1",
"html-loader": "0.4.5",
"html-webpack-harddisk-plugin": "0.1.0",
"html-webpack-plugin": "2.28.0",
"http-proxy-middleware": "*",
"http-server": "^0.10.0",
"image-webpack-loader": "3.3.1",
"imports-loader": "0.7.1",
"jshint-loader": "^0.8.4",
"raw-loader": "0.5.1",
"resolve-url-loader": "2.0.2",
"rollup": "^0.43.0",
"rollup-plugin-babel": "^2.7.1",
"rollup-plugin-node-resolve": "^3.0.0",
"sass-loader": "6.0.5",
"shelljs": "^0.7.7",
"ssh-webpack-plugin": "^0.1.7",
"style-loader": "0.17.0",
"svg-loader": "0.0.2",
"url-loader": "0.5.8",
"webpack": "3.0.0",
"webpack-dev-server": "^2.5.0",
"yargs": "^8.0.1"
},
"engines": {
"node": ">=0.10.0"
}
}
webpack config files: it's a folder with .babelrc, dev.js, server.js, prod.js, share.js and below is share.js file
const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {
rm
} = require('shelljs')
const pkg = require('../package.json')
const webpack = require('webpack')
const baseChunks = ['config', 'app']
const basePlugins = (chunks, enableHtml) => {
const html = enableHtml ?
[
new HtmlWebpackPlugin({
title: 'PMR Client',
filename: './index.html',
template: './src/client/index.ejs',
chunksSortMode: (a, b) => chunks.indexOf(a.names[0]) - chunks.indexOf(b.names[0]),
alwaysWriteToDisk: true,
env: process.env.NODE_ENV || 'development',
}),
new HtmlWebpackHarddiskPlugin(),
] :
[]
return [
new ExtractTextPlugin('style.css'),
...html,
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
}),
new webpack.optimize.ModuleConcatenationPlugin(),
]
}
const baseEntries = {
app: './src/app/index.js',
config: `./clients/${process.env.CLIENT}/config.js`,
}
const baseOutput = () => {
const output = {
path: path.join(__dirname, `../dist/cdn/${pkg.version}`),
filename: '[name].bundle.js',
}
if (process.env.NODE_ENV === 'production' && process.env.UPLOAD === 'true') {
output['publicPath'] = `//streamlinedoffice.com/pmr/cdn/${pkg.version}/`
}
return output
}
const sourceMap = (process.env.NODE_ENV === 'production') ? '' : 'sourceMap'
const getBaseConfig = ({
plugins = [],
chunks = [],
entries = baseEntries,
enableHtml = false
} = {}) => {
rm('-rf', path.resolve(__dirname, '../dist'))
const ch = [...baseChunks, ...chunks]
return {
entry: entries,
output: baseOutput(),
target: 'web',
devtool: 'cheap-module-eval-source-map',
plugins: [...basePlugins(ch, enableHtml), ...plugins],
module: {
rules: [{
test: /\.html$/,
use: [{
loader: 'html-loader',
options: {
minimize: true,
root: '../src/assets/images',
},
}, ],
},
{
test: [/src\/app.*\.js$/, /client.*\.js$/],
exclude: /node_modules/,
use: {
loader: 'babel-loader',
// loader:'echo-loader',
},
},
{
test: [/\.css$/, /\.scss$/],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', `sass-loader?${sourceMap}`],
}),
},
{
test: /bootstrap-sass\/assets\/javascripts\//,
use: 'imports-loader?jQuery=jquery'
},
// Font Definitions
{
test: /\.svg$/,
loader: 'url-loader?limit=65000&mimetype=image/svg+xml&name=public/fonts/[name].[ext]',
},
{
test: /\.woff$/,
loader: 'url-loader?limit=65000&mimetype=application/font-woff&name=public/fonts/[name].[ext]',
},
{
test: /\.woff2$/,
loader: 'url-loader?limit=65000&mimetype=application/font-woff2&name=public/fonts/[name].[ext]',
},
{
test: /\.[ot]tf$/,
loader: 'url-loader?limit=65000&mimetype=application/octet-stream&name=public/fonts/[name].[ext]',
},
{
test: /\.eot$/,
loader: 'url-loader?limit=65000&mimetype=application/vnd.ms-fontobject&name=public/fonts/[name].[ext]',
},
{
test: /\.png$/,
use: {
loader: 'url-loader?limit=8192',
},
},
{
test: /\.(jpe?g|gif)$/i,
use: [
'file-loader?hash=sha512&digest=hex&publicPath=../&name=./img/[hash].[ext]',
{
loader: 'image-webpack-loader',
query: {
gifsicle: {
interlaced: false,
},
progressive: true,
optipng: {
optimizationLevel: 7,
},
bypassOnDebug: true,
},
},
],
},
],
},
}
}
module.exports = getBaseConfig
Below is the script used to build the app.bundle.js, vendor.bundle.js an d manifest.bundle.js files (this file is on scripts/cmds/prod.js)
import {
echo,
head,
execStrict,
ls,
copy,
rmdir,
mkdir
} from '../utils'
import fs from 'fs-extra'
import path from 'path'
import {
rollup
} from 'rollup'
import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
const compiler = client =>
rollup({
entry: `./clients/${client}/config.js`,
plugins: [
resolve(),
babel({
exclude: 'node_modules/**',
babelrc: false,
presets: [
['env',
{
modules: false,
targets: {
browsers: [
"last 3 versions",
"Explorer 9",
],
},
},
],
],
plugins: ['external-helpers'],
externalHelpers: true
}),
],
}).then(bundle =>
bundle.write({
format: 'cjs',
dest: path.join(__dirname, `../../.tmpClients/${client}/config.js`),
})
)
const getClients = () =>
fs
.readdirSync('./clients')
.filter(file => fs.lstatSync(path.join('./clients', file)).isDirectory())
const handleCommand = async ({
upload = true,
optimize = true
}) => {
echo(head('Building clients...'))
const clients = getClients()
mkdir('./.tmpClients')
const promises = clients.map(client => {
compiler(client)
})
await Promise.all(promises)
echo(head('Run production build'))
await execStrict(
`cross-env UPLOAD=${upload} OPTIMIZE=${optimize} NODE_ENV=production webpack --config webpack/prod.js --progress --colors --define process.env.NODE_ENV="'production'"`
)
echo(head('Copying config files to clients'))
ls('./.tmpClients').forEach(client => {
copy({
origin: `./.tmpClients/${client}/*.js`,
dest: `./dist/clients/${client}`,
})
copy({
origin: `./dist/clients/${client}/index.html`,
dest: `./dist/clients/${client}/default.aspx`,
})
copy({
origin: './src/client/favicon.ico',
dest: `./dist/clients/${client}/`,
})
})
rmdir('./.tmpClients')
}
exports.command = 'build'
exports.describe = 'Create a production build'
exports.handler = handleCommand
exports.builder = {
upload: {
describe: 'Upload the production files to the cdn',
type: 'boolean',
default: true,
},
optimize: {
describe: 'Toggle the production optimizations, useful to check the production build as development',
type: 'boolean',
default: true,
},
}
below is .babelrc in webpack folder:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "dynamic-import-node"]
}
below .babelrc is in global same level as webpack folder
{
"presets": [
["env", {
"targets": {
"browsers": ["last 3 versions","Explorer 9"]
}
}]
],
"plugins": ["transform-runtime", "transform-object-rest-spread",
["angularjs-annotate", {
"explicitOnly": true
}]]
}
if anyone ran into such similar issue are know how to resolve it do share your inputs. Any help is much appreciated. Thanks

Unable to use webpack alias with Jest testing - Invariant Violation: Target container is not a DOM element

I've created a new repo that replicates this problem found here: https://github.com/davidRoussov/jest-webpack-alias
It's a React app bootstrapped using create-react-app, but it has been ejected. The error I'm getting when I run npm run test is this:
FAIL src\components\Parent.test.js
● Test suite failed to run
Invariant Violation: Target container is not a DOM element.
at invariant (node_modules/fbjs/lib/invariant.js:42:15)
at Object.<anonymous> (src/index.js:7:20)
at Object.<anonymous> (src/components/Parent.js:2:14)
at Object.<anonymous> (src/components/Parent.test.js:2:15)
at process._tickCallback (internal/process/next_tick.js:103:7)
The component being tested, Parent.js:
import React, { Component } from 'react';
import Child from '#/components/Child';
class Parent extends Component {
render() {
return (
<div>
<Child/>
</div>
);
}
}
export default Parent;
The test, Parent.test.js:
import React from 'react';
import Parent from './Parent';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Parent/>
).toJSON();
expect(tree).toMatchSnapshot();
});
For the webpack config I've only added:
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
And:
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
'#': resolve('src')
},
The Jest config:
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleDirectories": ["node_modules"],
"modulePaths": ["src"],
"moduleNameMapper": {
"^#(.*)$": "<rootDir>/src",
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node"
]
},
Jest does not produce errors if import Child from '#/components/Child'; is replaced with import Child from './Child';
I hope it's not too late, you forgot to substitute the captured regex groups in the path , like so:
"moduleNameMapper": {
"^#(.*)$": "<rootDir>/src/$1",
},
Link to the documentation

Resources