Skip to content

Commit dc7460f

Browse files
authored
Merge pull request webpack#6079 from ooflorent/mock_hooks
Improve `PluginEnvironment` helper to support tapable's hooks
2 parents f3fdd26 + fa72f1f commit dc7460f

File tree

1 file changed

+41
-7
lines changed

1 file changed

+41
-7
lines changed

test/helpers/PluginEnvironment.js

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,48 @@
11
module.exports = function PluginEnvironment() {
2-
var events = [];
2+
const events = [];
3+
4+
function addEvent(name, handler) {
5+
events.push({
6+
name,
7+
handler
8+
});
9+
}
10+
11+
function getEventName(hookName) {
12+
// Convert a hook name to an event name.
13+
// e.g. `buildModule` -> `build-module`
14+
return hookName.replace(/[A-Z]/g, c => "-" + c.toLowerCase());
15+
}
316

417
this.getEnvironmentStub = function() {
18+
const hooks = new Map();
519
return {
6-
plugin: function(name, handler) {
7-
events.push({
8-
name,
9-
handler
10-
});
11-
}
20+
plugin: addEvent,
21+
// TODO: Figure out a better way of doing this
22+
// In the meanwhile, `hooks` is a `Proxy` which creates fake hooks
23+
// on demand. Instead of creating a dummy object with a few `Hook`
24+
// method, a custom `Hook` class could be used.
25+
hooks: new Proxy({}, {
26+
get(target, hookName) {
27+
let hook = hooks.get(hookName);
28+
if (hook === undefined) {
29+
const eventName = getEventName(hookName);
30+
hook = {
31+
tap(_, handler) {
32+
addEvent(eventName, handler);
33+
},
34+
tapAsync(_, handler) {
35+
addEvent(eventName, handler);
36+
},
37+
tapPromise(_, handler) {
38+
addEvent(eventName, handler);
39+
}
40+
};
41+
hooks.set(hookName, hook);
42+
}
43+
return hook;
44+
}
45+
})
1246
};
1347
};
1448

0 commit comments

Comments
 (0)