Skip to content

Commit

Permalink
Core: Warn when setting hooks for a different module
Browse files Browse the repository at this point in the history
This will become an error in QUnit 3.

Ref #1576.
Closes #1586.
  • Loading branch information
raycohen authored Apr 10, 2021
1 parent 9356109 commit f9ce52b
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/module.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import Logger from "./logger";

import config from "./core/config";

import SuiteReport from "./reports/suite";
Expand Down Expand Up @@ -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 );
};
}
Expand Down
9 changes: 9 additions & 0 deletions test/cli/fixtures/expected/tap-outputs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`
};
9 changes: 9 additions & 0 deletions test/cli/fixtures/incorrect-hooks-warning/test.js
Original file line number Diff line number Diff line change
@@ -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 );
} );
} );
} );
9 changes: 9 additions & 0 deletions test/cli/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ] );
} );
} );

0 comments on commit f9ce52b

Please sign in to comment.