UNPKG

2.4 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) {
61 compiler.run(function(err, stats) {
62 if (stats.compilation.errors.length) {
63 throw new Error(stats.compilation.errors);
64 }
65
66 const bundleJs = stats.compilation.assets["bundle.js"].source();
67
68 jsdom.env({
69 html: jsdomHtml,
70 src: [bundleJs],
71 virtualConsole: jsdom.createVirtualConsole().sendTo(console),
72 done: function(err, window) {
73 if (typeof actual === 'function') {
74 assert.equal(actual.apply(window), expected);
75 } else {
76 assert.equal(window.document.head.innerHTML.trim(), expected);
77 }
78 // free memory associated with the window
79 window.close();
80
81 done();
82 }
83 });
84 });
85 }
86};
\No newline at end of file