Unit testing

Thus far, we have written a custom loader, followed the guidelines, and even got it running locally. The next step is testing. The following example is a simple unit testing procedure. It makes use of the babel-jest Jest framework and some other presets to allow the use of the import/export and async/await methods:

  1. We'll start by installing and saving these as something called devDependencies, like this:
npm install --save-dev jest babel-jest babel-preset-env

The previous command-line entry installs the Jest framework and Babel with Jest in development mode.

  1. Next, we must look at the configuration used in webpack.config.js concerning this particular unit testing procedure, as follows:
.babelrc
{
"presets": [[
"env",
{
"targets": {
"node": "4"
}
}
]]
}
  1. The function of the loader in the example is to process a text file and replace any instance of [name] with the option given to the loader. It then outputs a valid JavaScript module containing the text as its default export, as seen in the following example inside of src/loader.js:
import { getOptions } from 'loader-utils';
export default function loader(source) {
const options = getOptions(this);
source = source.replace(/[name]/g, options.name);
return `export default ${ JSON.stringify(source) }`;
}
  1. This loader will be used to process the following text file, called test/example.txt:
Hi Reader!
  1. The next step is a little more complicated. It uses the Node.js API and memory-fs to execute Webpack. This will avoid content being output to the local hard drive (very handy to know) and gives us access to statistical data that can be used to take hold of our transformed module. It begins with the following command line:
npm install --save-dev webpack memory-fs
  1. Once it's installed, there's some work we need to do on its associated compiler script. Use the following test/compiler.js file:
import path from 'path';
import webpack from 'webpack';
import memoryfs from 'memory-fs';
export default (fixture, options = {}) => {
const compiler = webpack({
context: __dirname,
entry: `./${fixture}`,
output: {
path: path.resolve(__dirname),
filename: 'bundle.js',
},
module: {
rules: [{
test: /.txt$/,
use: {
loader: path.resolve(__dirname, '../src/loader.js'),
options: {
name: 'Alice'
}
}
}]
}
});
compiler.outputFileSystem = new memoryfs();
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) reject(err);
if (stats.hasErrors()) reject(new Error(stats.toJson().errors));
resolve(stats);
});
});
};

In the previous example, we inlined our configuration, but a configuration as a parameter to the export function can also be accepted. This allows the testing of multiple setups using the same compiler module.

  1. This being done, we can now write our test and add an npm script to run it. Let's begin by adding the following code to our test/loader.test.js file:
import compiler from './compiler.js';
test('Inserts name and outputs JavaScript', async () => {
const stats = await compiler('example.txt');
const output = stats.toJson().modules[0].source;
expect(output).toBe('export default "Hi Reader!\n"');
});
package.json
{
"scripts": {
"test": "jest"
}
}

The preceding code block shows the testing function that loads in the example text, should the program work correctly.

Everything should now be in place.

  1. The code can now be run, and we'll check whether the new loader has passed the test by running an npm build in the command line and viewing the command-line window, as follows:
 Inserts name and outputs JavaScript (229ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.853s, estimated 2s
Ran all test suites.

If you see something like the preceding text in the corresponding file, then it passed. Well done! 

At this point, you should be able to develop, test, and deploy your loaders. Don't forget to share your creations with the rest of the Webpack community and help expand the capabilities of developers everywhere, and make your mark at the same time.

We've covered a huge amount in this guide and I suppose you feel like an expert, having built custom libraries and loaders, but making live coding hacks would make your skillset even more impressive. These are useful to know, especially on custom jobs where workarounds and makeshift approaches are more likely than tried-and-tested code, so let's dive right in!

..................Content has been hidden....................

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