Skip to content

Commit

Permalink
fix: disallow hook defintions in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed May 3, 2020
1 parent 2e8f8d5 commit 5b8382b
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -10,6 +10,7 @@
- `[jest-circus, jest-console, jest-jasmine2, jest-reporters, jest-util, pretty-format]` Fix time durating formatting and consolidate time formatting code ([#9765](https://github.com/facebook/jest/pull/9765))
- `[jest-circus]` [**BREAKING**] Fail tests if a test takes a done callback and have return values ([#9129](https://github.com/facebook/jest/pull/9129))
- `[jest-circus]` [**BREAKING**] Throw a proper error if a test / hook is defined asynchronously ([#8096](https://github.com/facebook/jest/pull/8096))
- `[jest-circus]` Throw more descriptive error if hook is defined inside test
- `[jest-config, jest-resolve]` [**BREAKING**] Remove support for `browser` field ([#9943](https://github.com/facebook/jest/pull/9943))

### Chore & Maintenance
Expand Down
14 changes: 14 additions & 0 deletions e2e/__tests__/nestedTestDefinitions.test.ts
Expand Up @@ -55,3 +55,17 @@ test('print correct message when nesting describe inside it', () => {
'Cannot nest a describe inside a test. Describe block "inner describe" cannot run because it is nested within "test".',
);
});

test('print correct message when nesting a hook inside it', () => {
if (!isJestCircusRun()) {
return;
}

const result = runJest('nested-test-definitions', ['nestedHookInTest']);

expect(result.exitCode).toBe(1);

expect(result.stderr).toContain(
'Hooks cannot be defined inside tests. Hook of type "beforeEach" is nested within "test".',
);
});
18 changes: 18 additions & 0 deletions e2e/nested-test-definitions/__tests__/nestedHookInTest.js
@@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

const {getTruthy} = require('../index');

test('test', () => {
expect(getTruthy()).toBeTruthy();

beforeEach(() => {
// nothing to see here
});
});
9 changes: 8 additions & 1 deletion packages/jest-circus/src/eventHandler.ts
Expand Up @@ -88,8 +88,15 @@ const eventHandler: Circus.EventHandler = (
break;
}
case 'add_hook': {
const {currentDescribeBlock, hasStarted} = state;
const {currentDescribeBlock, currentlyRunningTest, hasStarted} = state;
const {asyncError, fn, hookType: type, timeout} = event;

if (currentlyRunningTest) {
throw new Error(
`Hooks cannot be defined inside tests. Hook of type "${type}" is nested within "${currentlyRunningTest.name}".`,
);
}

const parent = currentDescribeBlock;

if (hasStarted) {
Expand Down

0 comments on commit 5b8382b

Please sign in to comment.