UNPKG

2.46 kBJavaScriptView Raw
1// Node v4 requires "use strict" to allow block scoped let & const
2"use strict";
3
4var MemoryFS = require("memory-fs");
5var realFs = require("fs");
6var webpack = require("webpack");
7var path = require("path");
8var jsdom = require("jsdom");
9
10var assert = require("assert");
11
12var compiler;
13var jsdomHtml;
14
15module.exports = {
16 setup: function(webpackConfig, _jsdomHtml) {
17 let fs = new MemoryFS();
18
19 jsdomHtml = _jsdomHtml;
20
21 // Makes webpack resolve style-loader to local folder instead of node_modules
22 Object.assign(webpackConfig, {
23 resolveLoader: {
24 alias: {
25 "style-loader": path.resolve(__dirname, "../")
26 }
27 }
28 });
29
30 compiler = webpack(webpackConfig);
31
32 // Tell webpack to use our in-memory FS
33 compiler.inputFileSystem = fs;
34 compiler.outputFileSystem = fs;
35 compiler.resolvers.normal.fileSystem = fs;
36 compiler.resolvers.context.fileSystem = fs;
37
38 ["readFileSync", "statSync"].forEach(fn => {
39 // Preserve the reference to original function
40 fs["mem" + fn] = fs[fn];
41
42 compiler.inputFileSystem[fn] = function(_path) {
43 // Fallback to real FS if file is not in the memoryFS
44 if (fs.existsSync(_path)) {
45 return fs["mem" + fn].apply(fs, arguments);
46 } else {
47 return realFs[fn].apply(realFs, arguments);
48 }
49 };
50 });
51
52 return fs;
53 },
54
55 /*
56 * @param {string} expected - Expected value.
57 * @param {function} done - Async callback from Mocha.
58 * @param {function} actual - Executed in the context of jsdom window, should return a string to compare to.
59 */
60 runCompilerTest: function(expected, done, actual, selector) {
61 selector = selector || "head"
62 compiler.run(function(err, stats) {
63 if (stats.compilation.errors.length) {
64 throw new Error(stats.compilation.errors);
65 }
66
67 const bundleJs = stats.compilation.assets["bundle.js"].source();
68
69 jsdom.env({
70 html: jsdomHtml,
71 src: [bundleJs],
72 virtualConsole: jsdom.createVirtualConsole().sendTo(console),
73 done: function(err, window) {
74 if (typeof actual === 'function') {
75 assert.equal(actual.apply(window), expected);
76 } else {
77 assert.equal(window.document.querySelector(selector).innerHTML.trim(), expected);
78 }
79 // free memory associated with the window
80 window.close();
81
82 done();
83 }
84 });
85 });
86 }
87};