diff --git a/src/module.js b/src/module.js index cfa21ff0a..ad417010a 100644 --- a/src/module.js +++ b/src/module.js @@ -1,3 +1,5 @@ +import Logger from "./logger"; + import config from "./core/config"; import SuiteReport from "./reports/suite"; @@ -94,6 +96,11 @@ function processModule( name, options, executeNow, modifiers = {} ) { function setHookFunction( module, hookName ) { return function setHook( callback ) { + if ( config.currentModule !== module ) { + Logger.warn( "The `" + hookName + "` hook was called inside the wrong module. " + + "Instead, use hooks provided by the callback to the containing module." + + "This will become an error in QUnit 3.0." ); + } module.hooks[ hookName ].push( callback ); }; } diff --git a/test/cli/fixtures/expected/tap-outputs.js b/test/cli/fixtures/expected/tap-outputs.js index bf8ee7edd..d027ca0f7 100644 --- a/test/cli/fixtures/expected/tap-outputs.js +++ b/test/cli/fixtures/expected/tap-outputs.js @@ -331,5 +331,14 @@ ok 3 module B > test D # pass 2 # skip 1 # todo 1 +# fail 0`, + + "qunit incorrect-hooks-warning/test.js": +`TAP version 13 +ok 1 module providing hooks > module not providing hooks > has a test +1..1 +# pass 1 +# skip 0 +# todo 0 # fail 0` }; diff --git a/test/cli/fixtures/incorrect-hooks-warning/test.js b/test/cli/fixtures/incorrect-hooks-warning/test.js new file mode 100644 index 000000000..292fe1fee --- /dev/null +++ b/test/cli/fixtures/incorrect-hooks-warning/test.js @@ -0,0 +1,9 @@ +QUnit.module( "module providing hooks", function( hooks ) { + QUnit.module( "module not providing hooks", function() { + // eslint-disable-next-line qunit/no-hooks-from-ancestor-modules + hooks.beforeEach( function() {} ); + QUnit.test( "has a test", function( assert ) { + assert.true( true ); + } ); + } ); +} ); diff --git a/test/cli/main.js b/test/cli/main.js index 9484482f5..89edc4057 100644 --- a/test/cli/main.js +++ b/test/cli/main.js @@ -311,4 +311,13 @@ QUnit.module( "CLI Main", () => { assert.equal( execution.stdout, expectedOutput[ command ] ); } ); } ); + + QUnit.test( "warns about incorrect hook usage", async assert => { + const command = "qunit incorrect-hooks-warning/test.js"; + const execution = await execute( command ); + + assert.equal( execution.code, 0 ); + assert.equal( execution.stderr, "The `beforeEach` hook was called inside the wrong module. Instead, use hooks provided by the callback to the containing module.This will become an error in QUnit 3.0.", "The warning shows" ); + assert.equal( execution.stdout, expectedOutput[ command ] ); + } ); } );