question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Compilation error on component testing

See original GitHub issue

Current behavior

I followed the guide to implement component testing. Unfortunately when I run npx cypress open-ct I see the following error.

First I thought it’s not compatible with react-refresh/babel webpack plugin, but after I removed it I saw the same issue.

Compiled with problems:X

ERROR in ./src/components/button/button.spec.jsx 7:14

Module parse failed: Unexpected token (7:14)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| describe('BUTTON', () => {
|     it('Button', () => {
>         mount(<Button text="Test button"/>)
|         cy.get('button').contains('Test button').click()
|     })

Here are my files:

webpack.config.js
const Path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const ESLintPlugin = require("eslint-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const webpack = require("webpack");

const dist = Path.resolve(__dirname, "build");

const config = (env, argv) => {
    const isDevelopment = argv.mode !== "production";
    const configPath = env.hasOwnProperty("config") ? Path.resolve(__dirname, env.config) : Path.resolve(__dirname, "./config/local/config.json");

    console.info("Config Path: ", configPath);

    return {
        entry: "./src/main.jsx",
        resolve: {
            extensions: [".js", ".jsx"],
            alias: {
                config: configPath
            }
        },
        output: {
            path: dist,
            publicPath: "/",
            filename: "bundles/[name].[contenthash].bundle.js"
        },
        mode: isDevelopment ? "development" : "production",
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    use: [
                        {
                            loader: require.resolve("babel-loader"),
                            options: {
                                plugins: [isDevelopment && require.resolve("react-refresh/babel")].filter(Boolean)
                            }
                        }
                    ],
                    exclude: /node_modules/
                },
                {
                    test: /\.css$/,
                    use: ["style-loader", "css-loader"]
                },
                {
                    test: /\.(scss|sass)$/,
                    use: ["style-loader", "css-loader", "sass-loader"]
                },
                {
                    test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader",
                    options: {
                        limit: 10000,
                        mimetype: "application/font-woff",
                        name: "fonts/[name].[ext]"
                    }
                },
                {
                    test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader",
                    options: {
                        limit: 10000,
                        mimetype: "application/font-woff",
                        name: "fonts/[name].[ext]"
                    }
                },
                {
                    test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader",
                    options: {
                        limit: 10000,
                        mimetype: "application/octet-stream",
                        name: "fonts/[name].[ext]"
                    }
                },
                {
                    test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "file-loader",
                    options: {
                        name: "fonts/[name].[ext]"
                    }
                },
                {
                    test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader",
                    options: {
                        limit: 10000,
                        mimetype: "image/svg+xml",
                        name: "svgs/[name].[ext]"
                    }
                }
            ]
        },
        optimization: {
            splitChunks: {
                chunks: "all",
                maxInitialRequests: Infinity,
                minSize: 0,
                cacheGroups: {
                    vendor: {
                        test: /[\\/]node_modules[\\/]/,
                        name(module) {
                            // get the name. E.g. node_modules/packageName/not/this/part.js
                            // or node_modules/packageName
                            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

                            // npm package names are URL-safe, but some servers don't like @ symbols
                            return `npm.${packageName.replace("@", "")}`;
                        }
                    }
                }
            },
            minimize: !isDevelopment
        },
        plugins: [
            new HtmlWebpackPlugin({ template: "./src/index.html" }),
            new CopyPlugin({
                patterns: [{ from: "./src/static", to: "static" }]
            }),
            new ESLintPlugin({
                emitWarning: !isDevelopment
            }),
            new ReactRefreshWebpackPlugin(),
            new webpack.ProvidePlugin({
                config: 'config'
            })
        ],
        devtool: "source-map",
        devServer: {
            hot: true,
            static: {
                directory: dist
            },
            port: 3000,
            https: true,
            historyApiFallback: true
        }
    };
};

module.exports = (env, argV) => config(env, argV);
.babelrc
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
  "@babel/plugin-transform-runtime"
  ]
}


button.spec.jsx
import React from 'react'
import { mount } from '@cypress/react'
import Button from "./button.jsx";

describe('Test button', () => {
    it('Button', () => {
        mount(<Button text="Test button"/>)
        cy.get('button').contains('Test button').click()
    })
})

cypress.json
{
    "baseUrl": "https://localhost:8000",
    "component": {
        "componentFolder": "src",
        "testFiles": "**/*.spec.{js,jsx}"
    }
}
cypress/plugins/index.js
module.exports = (on, config) => {
    if (config.testingType === 'component') {
        const { startDevServer } = require('@cypress/webpack-dev-server')

        const webpackConfig = require('../../webpack.config.js')

        on('dev-server:start', (options) =>
            startDevServer({ options, webpackConfig })
        )
        return webpackConfig
    }
};

Desired behavior

I expect that the test is going to fail or succeed without an compiling error.

Test code to reproduce

Cypress Version

8.5.0

Other

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:3
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
lubomirKavetskiycommented, Dec 12, 2021

@johnjayhopley could you plz share here that separate webpack config file? Looks like I have the same problem.

3reactions
shellsrodscommented, Mar 31, 2022

For anyone who gets this error, You may need an additional loader to handle the result of these loaders will need to add a flag "jsx": "react" in tsconfig.json

Read more comments on GitHub >

github_iconTop Results From Across the Web

Compilation Error in Test A When Executing Test B
PROBLEM. My project contains two or more tests that contain coded steps. I receive a compilation error for Test A when I try...
Read more >
How do I write a test assuring a compilation error?
There isn't currently a way of indicating that a regular test should not compile. And by the look of related issues (#521 and...
Read more >
Component Testing for C compilation results in MS ... - IBM
When building a ptu file with such STUB declaration, MS compiler will generate C2082 error - redefinition of formal parameter 'res'. This is ......
Read more >
Component testing scenarios - Angular
Error : This test module uses the component BannerComponent which is using a "templateUrl" or "styleUrls", but they were never compiled.
Read more >
Error Messages | Cypress Documentation
Test File Errors No tests found This message means that Cypress was unable ... Cypress encountered an error when compiling and/or bundling your...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found