How to run unit test with webpack?

Viewed 3315

I have a Node Js server that I bundled with webpack with the following config:

module.exports = {
    entry: './build/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
        devtoolModuleFilenameTemplate: '../[resource-path]',
    },

    target: 'node',
    node: {
        __dirname: true,
    },
    externals: {
        kcors: 'kcors',
        'koa-bodyparser': 'koa-bodyparser'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: ["source-map-loader"],
                enforce: "pre"
            },
        ],
    },
    resolve: {
        extensions: ['.js'],
    },
    // plugins: [
    //     new webpack.DefinePlugin({
    //         "process.env": JSON.stringify(dotenv.parsed)
    //     }),
    // ],
    devtool: 'eval-source-map'
};

This created a single file main.js inside dist

Everything looks good so far. I manually tested the server and it works.

Now, before I used webpack, I have a set of unit tests that I named with the .spec.js suffix inside my entry folder (the build/ folder) and each .js file has each own .spec file sibling located in the same directory of the .js.

To run theses unit test, I used mocha with the command: mocha build/**/*.spec.js --recursive --timeout 20000

Since I am new to webpack and the concept of bundling, how do I run the same tests from the main.js file ? I want to make sure that all tests are still passing in the bundled file

1 Answers

use

npm install mocha mocha-loader 

config your webpack.config.js file like:

module.exports = {
entry: './entry.js',
output: {
 path: __dirname,
 filename: 'bundle.js',
},
module: {
 rules: [
   {
     test: /test\.js$/,
     use: 'mocha-loader',
     exclude: /node_modules/,
   },
 ],
},
};

then, call your test file from your main file like: (into app.js)

import test from 'allMyTests';
Related