Skip to content

Latest commit

 

History

History
72 lines (53 loc) · 2.64 KB

prefer-explicit-assert.md

File metadata and controls

72 lines (53 loc) · 2.64 KB

Suggest using explicit assertions rather than just getBy* queries (testing-library/prefer-explicit-assert)

Testing Library getBy* queries throw an error if the element is not found. Some users like this behavior to use the query itself as an assert for the element existence in their tests, but other users don't and prefer to explicitly assert the element existence, so this rule is for users from the latter.

Rule Details

This rule aims to encourage users to explicitly assert existence of elements in their tests rather than just use getBy* queries and expect it doesn't throw an error so it's easier to understand what's the expected behavior within the test.

Examples of incorrect code for this rule:

// just calling `getBy*` query expecting not to throw an error as an
// assert-like method, without actually either using the returned element
// or explicitly asserting
getByText('foo');

const utils = render(<Component />);
utils.getByText('foo');

Examples of correct code for this rule:

// wrapping the get query within a `expect` and use some matcher for
// making the assertion more explicit
expect(getByText('foo')).toBeDefined();

const utils = render(<Component />);
expect(utils.getByText('foo')).toBeDefined();

// even more explicit if you use `@testing-library/jest-dom` matcher
// for checking the element is present in the document
expect(queryByText('foo')).toBeInTheDocument();

// Doing something with the element returned without asserting is absolutely fine
await waitForElement(() => getByText('foo'));
fireEvent.click(getByText('bar'));
const quxElement = getByText('qux');

Options

This rule has one option:

  • assertion: this string allows defining the preferred assertion to use with getBy* queries. By default, any assertion is valid (toBeTruthy, toBeDefined, etc.). However, they all assert slightly different things. This option ensures all getBy* assertions are consistent and use the same assertion. This rule only allows defining a presence matcher (toBeInTheDocument, toBeTruthy, or toBeDefined), but checks for both presence and absence matchers (not.toBeFalsy and not.toBeNull). This means other assertions such as toHaveValue or toBeDisabled will not trigger this rule since these are valid uses with getBy*.

    "testing-library/prefer-explicit-assert": ["error", {"assertion": "toBeInTheDocument"}],

When Not To Use It

If you prefer to use getBy* queries implicitly as an assert-like method itself, then this rule is not recommended.

Further Reading