Setting up your project with Mocha

We will use two things to write our unit tests: Mocha and Chai. Mocha is the process that makes all of your tests run, and Chai is a library that allows us to write nice-looking assertions. An assertion is effectively a statement saying that a behavior works as intended; the most basic of these is equals, which takes the actual equals expected format. Everything else is effectively just syntactic sugar for this assertion and makes your tests (debatably) nicer to read.

Install all of them to your project first, along with a few other goodies:

$ npm install mocha chai mocha-loader --save-dev
Why do we keep using --save-dev instead of just --save in this chapter? We use --save-dev because these are developer tools that only run in the developer environment. They shouldn't be part of the distributed code.

We will also create a new Webpack config file for testing. Create a file called webpack.test.config.js in your project root and add the following to it:

const path = require('path'); 
module.exports = [
{
output: {
path: path.resolve(__dirname, 'build'),
publicPath: '/assets/',
filename: 'bundle.js',
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /.ts?$/,
exclude: [/(node_modules|bower_components)/],
loader: 'ts-loader',
},
{
test: /.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
},
],
},
},
];

Let's get a feel for BDD-style development with Mocha and Chai by updating our TypeScript class from earlier with a few new behaviors. Also, add the following to the scripts stanza of package.json:

"start-tests": "webpack-dev-server --config webpack.test.config.js 'mocha-loader!./lib/chapter9/index.spec.js' --inline"

Now, you can run and develop tests with the server running in the background, by typing the following:

$ npm run start-tests
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset