How to run unit test with webpack?

Member

by denis , in category: Javascript , 16 days ago

How to run unit test with webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 15 days ago

@denis 

To run unit tests with webpack, you can use a testing framework such as Jest, Mocha, or Karma. Here is a general guide on how to run unit tests with webpack using Jest as an example:

  1. Install Jest and any necessary dependencies:
1
npm install jest webpack jest-cli babel-jest @babel/preset-env --save-dev


  1. Create a webpack configuration file (webpack.config.js) to bundle your test files:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
module.exports = {
  entry: './test/**/*.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'test.bundle.js'
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
};


  1. Add a script in your package.json to run Jest with webpack:
1
2
3
"scripts": {
  "test": "jest --config=jest.config.js"
}


  1. Create a Jest configuration file (jest.config.js) to specify the test environment and setup files:
1
2
3
4
module.exports = {
  testEnvironment: 'node',
  setupFilesAfterEnv: ['./jest.setup.js']
};


  1. Create a setup file (jest.setup.js) to configure Jest with webpack:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const webpack = require('webpack');
const config = require('./webpack.config.js');

module.exports = async () => {
  await new Promise((resolve, reject) => {
    webpack(config, (err, stats) => {
      if (err || stats.hasErrors()) {
        reject(err || stats.toJson().errors);
      } else {
        resolve();
      }
    });
  });
};


  1. Write your unit tests using Jest syntax and run them with the following command:
1
npm test


This will bundle your test files with webpack and run them using Jest. You can customize this setup further based on your specific requirements and testing framework.