How to run tests after compile webpack
October 27, 2018
The problem
I'm using webpack for compiling and bundling in one hand. In the other hand I'm using jest for testing.
I want to run the tests after each time that any file was changed (and compiled).
The solution
The solution has 3 steps of modifications the webpack.config.js file:
- Add the tests entry
- Answer the question How to run a code on each file changing in webpack?
- Call for running the tests
Step 1
Add an entry:
1entry: {2 // ...3 // add this to let webpack watch on the test files changes4 tests: "./test/path-to-the-tests-entry.js"5}
Step 2
To extend the functionality of webpack we can use a plugin. For our usage we can simply add it directly to the plugins section.
The only method we should implement in our plugin is apply
. In this method we will register to afterCompile
hook so in each compile we will run our code.
1plugins: [2 {3 // add a custom webpack plugin. For more info: https://webpack.js.org/concepts/plugins/4 apply: compiler => {5 // add a hook to run a callback after each compile6 compiler.hooks.afterCompile.tap('jest', compilation => {7 // in this part we will run the tests8 }9 }10 }11]
Step 3
Run
1spawn('npm', ['test'], {stdio:'inherit'});
I'm using spawn
and {stdio:'inherit'}
to keep the original colors which the terminal should use. (Thanks for the answer: https://stackoverflow.com/a/20145153/863110)
And all togather:
1const { spawn } = require("child_process")2
3module.exports = {4 entry: {5 // ...6 // add this to let webpack watch on the test files changes7 tests: "./test/path-to-the-tests-entry.js",8 },9 // ..10 plugins: [11 {12 // add a custom webpack plugin. For more info: https://webpack.js.org/concepts/plugins/13 apply: compiler => {14 // add a hook to run a callback after each compile15 compiler.hooks.afterCompile.tap("jest", compilation => {16 // run `npm test` using `spawn` to keep the format of the terminal just like you run it manually.17 // for more info: https://stackoverflow.com/a/20145153/86311018 spawn("npm", ["test"], { stdio: "inherit" })19 })20 },21 },22 ],23}