Skip to content

Latest commit

 

History

History
84 lines (54 loc) · 1.78 KB

require-hook.md

File metadata and controls

84 lines (54 loc) · 1.78 KB

Require setup and teardown to be within a hook (vitest/require-hook)

⚠️ This rule warns in the 🌐 all config.

It's common when writing tests to need to perform a particular setup work before and after a test suite run. Because Vitest executes all describe handlers in a test file before it executes any of the actual tests, it's important to ensure setup and teardown work is done inside before* and after* handlers respectively, rather than inside the describe blocks.

Details

This rule flags any expression that is either at the toplevel of a test file or directly within the body of a describe except the following:

  • import statements
  • const variables
  • let declarations and initializations to null or undefined
  • Classes
  • Types

This rule flags any function within in a describe block and suggest wrapping them in one of the four lifecycle hooks.

The following patterns are considered warnings:

import { database } from './api'

describe('foo', () => {
   database.connect()

   test('bar', () => {
	 // ...
   })

   database.disconnect()
})

The following patterns are not warnings:

describe('foo', () => {
   before(() => {
	 database.connect()
   })

   test('bar', () => {
	 // ...
   })
})

Options

If there are methods that you want to call outside of hooks and tests, you can mark them as allowed using the allowedFunctionCalls option.

{
  "vitest/require-hook": ["error", {
	"allowedFunctionCalls": ["database.connect"]
  }]
}

The following patterns are not warnings because database.connect is allowed:

import { database } from './api'

describe('foo', () => {
   database.connect()

   test('bar', () => {
	 // ...
   })

   database.disconnect()
})