| 1 | # Require test cases and hooks to be inside a `describe` block (`require-top-level-describe`)
|
|---|
| 2 |
|
|---|
| 3 | Jest allows you to organise your test files the way you want it. However, the
|
|---|
| 4 | more your codebase grows, the more it becomes hard to navigate in your test
|
|---|
| 5 | files. This rule makes sure you provide at least a top-level `describe` block in
|
|---|
| 6 | your test file.
|
|---|
| 7 |
|
|---|
| 8 | ## Rule Details
|
|---|
| 9 |
|
|---|
| 10 | This rule triggers a warning if a test case (`test` and `it`) or a hook
|
|---|
| 11 | (`beforeAll`, `beforeEach`, `afterEach`, `afterAll`) is not located in a
|
|---|
| 12 | top-level `describe` block.
|
|---|
| 13 |
|
|---|
| 14 | The following patterns are considered warnings:
|
|---|
| 15 |
|
|---|
| 16 | ```js
|
|---|
| 17 | // Above a describe block
|
|---|
| 18 | test('my test', () => {});
|
|---|
| 19 | describe('test suite', () => {
|
|---|
| 20 | it('test', () => {});
|
|---|
| 21 | });
|
|---|
| 22 |
|
|---|
| 23 | // Below a describe block
|
|---|
| 24 | describe('test suite', () => {});
|
|---|
| 25 | test('my test', () => {});
|
|---|
| 26 |
|
|---|
| 27 | // Same for hooks
|
|---|
| 28 | beforeAll('my beforeAll', () => {});
|
|---|
| 29 | describe('test suite', () => {});
|
|---|
| 30 | afterEach('my afterEach', () => {});
|
|---|
| 31 | ```
|
|---|
| 32 |
|
|---|
| 33 | The following patterns are **not** considered warnings:
|
|---|
| 34 |
|
|---|
| 35 | ```js
|
|---|
| 36 | // In a describe block
|
|---|
| 37 | describe('test suite', () => {
|
|---|
| 38 | test('my test', () => {});
|
|---|
| 39 | });
|
|---|
| 40 |
|
|---|
| 41 | // In a nested describe block
|
|---|
| 42 | describe('test suite', () => {
|
|---|
| 43 | test('my test', () => {});
|
|---|
| 44 | describe('another test suite', () => {
|
|---|
| 45 | test('my other test', () => {});
|
|---|
| 46 | });
|
|---|
| 47 | });
|
|---|
| 48 | ```
|
|---|
| 49 |
|
|---|
| 50 | You can also enforce a limit on the number of describes allowed at the top-level
|
|---|
| 51 | using the `maxNumberOfTopLevelDescribes` option:
|
|---|
| 52 |
|
|---|
| 53 | ```json
|
|---|
| 54 | {
|
|---|
| 55 | "jest/require-top-level-describe": [
|
|---|
| 56 | "error",
|
|---|
| 57 | {
|
|---|
| 58 | "maxNumberOfTopLevelDescribes": 2
|
|---|
| 59 | }
|
|---|
| 60 | ]
|
|---|
| 61 | }
|
|---|
| 62 | ```
|
|---|
| 63 |
|
|---|
| 64 | Examples of **incorrect** code with the above config:
|
|---|
| 65 |
|
|---|
| 66 | ```js
|
|---|
| 67 | describe('test suite', () => {
|
|---|
| 68 | it('test', () => {});
|
|---|
| 69 | });
|
|---|
| 70 |
|
|---|
| 71 | describe('test suite', () => {});
|
|---|
| 72 |
|
|---|
| 73 | describe('test suite', () => {});
|
|---|
| 74 | ```
|
|---|
| 75 |
|
|---|
| 76 | This option defaults to `Infinity`, allowing any number of top-level describes.
|
|---|
| 77 |
|
|---|
| 78 | ## When Not To Use It
|
|---|
| 79 |
|
|---|
| 80 | Don't use this rule on non-jest test files.
|
|---|