Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support for regular expressions in toHaveClass #563

Merged
merged 4 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -753,10 +753,12 @@ toHaveClass(...classNames: string[], options?: {exact: boolean})
```

This allows you to check whether the given element has certain classes within
its `class` attribute.
its `class` attribute. You must provide at least one class, unless you are
asserting that an element does not have any classes.

You must provide at least one class, unless you are asserting that an element
does not have any classes.
The list of class names may include strings and regular expressions. Regular
expressions are matched against each individual class in the target element, and
it is NOT matched against its full `class` attribute value as whole.

#### Examples

Expand All @@ -773,8 +775,11 @@ const noClasses = getByTestId('no-classes')

expect(deleteButton).toHaveClass('extra')
expect(deleteButton).toHaveClass('btn-danger btn')
expect(deleteButton).toHaveClass(/danger/, 'btn')
expect(deleteButton).toHaveClass('btn-danger', 'btn')
expect(deleteButton).not.toHaveClass('btn-link')
expect(deleteButton).not.toHaveClass(/link/)
expect(deleteButton).not.toHaveClass(/btn extra/) // It does not match

expect(deleteButton).toHaveClass('btn-danger extra btn', {exact: true}) // to check if the element has EXACTLY a set of classes
expect(deleteButton).not.toHaveClass('btn-danger extra', {exact: true}) // if it has more than expected it is going to fail
Expand Down
63 changes: 57 additions & 6 deletions src/__tests__/to-have-class.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,32 @@ test('.toHaveClass', () => {
).toThrowError(/(none)/)
})

test('.toHaveClass with regular expressions', () => {
const {queryByTestId} = renderElementWithClasses()

expect(queryByTestId('delete-button')).toHaveClass(/btn/)
expect(queryByTestId('delete-button')).toHaveClass(/danger/)
expect(queryByTestId('delete-button')).toHaveClass(
/-danger$/,
'extra',
/^btn-[a-z]+$/,
/\bbtn/,
)

// It does not match with "btn extra", even though it is a substring of the
// class "btn extra btn-danger". This is because the regular expression is
// matched against each class individually.
expect(queryByTestId('delete-button')).not.toHaveClass(/btn extra/)

expect(() =>
expect(queryByTestId('delete-button')).not.toHaveClass(/danger/),
).toThrowError()

expect(() =>
expect(queryByTestId('delete-button')).toHaveClass(/dangerous/),
).toThrowError()
})

test('.toHaveClass with exact mode option', () => {
const {queryByTestId} = renderElementWithClasses()

Expand All @@ -102,19 +128,21 @@ test('.toHaveClass with exact mode option', () => {
expect(queryByTestId('delete-button')).not.toHaveClass('btn extra', {
exact: true,
})
expect(
queryByTestId('delete-button'),
).not.toHaveClass('btn extra btn-danger foo', {exact: true})
expect(queryByTestId('delete-button')).not.toHaveClass(
'btn extra btn-danger foo',
{exact: true},
)

expect(queryByTestId('delete-button')).toHaveClass('btn extra btn-danger', {
exact: false,
})
expect(queryByTestId('delete-button')).toHaveClass('btn extra', {
exact: false,
})
expect(
queryByTestId('delete-button'),
).not.toHaveClass('btn extra btn-danger foo', {exact: false})
expect(queryByTestId('delete-button')).not.toHaveClass(
'btn extra btn-danger foo',
{exact: false},
)

expect(queryByTestId('delete-button')).toHaveClass(
'btn',
Expand Down Expand Up @@ -178,3 +206,26 @@ test('.toHaveClass with exact mode option', () => {
}),
).toThrowError(/Expected the element to have EXACTLY defined classes/)
})

test('.toHaveClass combining {exact:true} and regular expressions throws an error', () => {
const {queryByTestId} = renderElementWithClasses()

expect(() =>
expect(queryByTestId('delete-button')).not.toHaveClass(/btn/, {
exact: true,
}),
).toThrowError()

expect(() =>
expect(queryByTestId('delete-button')).not.toHaveClass(
/-danger$/,
'extra',
/\bbtn/,
{exact: true},
),
).toThrowError()

expect(() =>
expect(queryByTestId('delete-button')).toHaveClass(/danger/, {exact: true}),
).toThrowError()
})
24 changes: 18 additions & 6 deletions src/to-have-class.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ function getExpectedClassNamesAndOptions(params) {
const lastParam = params.pop()
let expectedClassNames, options

if (typeof lastParam === 'object') {
if (typeof lastParam === 'object' && !(lastParam instanceof RegExp)) {
expectedClassNames = params
options = lastParam
} else {
Expand All @@ -15,14 +15,16 @@ function getExpectedClassNamesAndOptions(params) {
}

function splitClassNames(str) {
if (!str) {
return []
}
if (!str) return []
return str.split(/\s+/).filter(s => s.length > 0)
}

function isSubset(subset, superset) {
return subset.every(item => superset.includes(item))
return subset.every(strOrRegexp =>
typeof strOrRegexp === 'string'
? superset.includes(strOrRegexp)
: superset.some(className => strOrRegexp.test(className)),
)
}

export function toHaveClass(htmlElement, ...params) {
Expand All @@ -31,10 +33,20 @@ export function toHaveClass(htmlElement, ...params) {

const received = splitClassNames(htmlElement.getAttribute('class'))
const expected = expectedClassNames.reduce(
(acc, className) => acc.concat(splitClassNames(className)),
(acc, className) =>
acc.concat(
typeof className === 'string' || !className
? splitClassNames(className)
: className,
),
[],
)

const hasRegExp = expected.some(className => className instanceof RegExp)
if (options.exact && hasRegExp) {
throw new Error('Exact option does not support RegExp expected class names')
}

if (options.exact) {
return {
pass: isSubset(expected, received) && expected.length === received.length,
Expand Down
6 changes: 5 additions & 1 deletion types/__tests__/jest/jest-custom-expect-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ customExpect(element).toHaveAttribute('attr', true)
customExpect(element).toHaveAttribute('attr', 'yes')
customExpect(element).toHaveClass()
customExpect(element).toHaveClass('cls1')
customExpect(element).toHaveClass('cls1', 'cls2', 'cls3', 'cls4')
customExpect(element).toHaveClass(/cls/)
customExpect(element).toHaveClass('cls1', 'cls2', /cls(3|4)/)
customExpect(element).toHaveClass('cls1', {exact: true})
customExpect(element).toHaveDisplayValue('str')
customExpect(element).toHaveDisplayValue(['str1', 'str2'])
Expand Down Expand Up @@ -94,3 +95,6 @@ customExpect(element).toHaveErrorMessage(

// @ts-expect-error The types accidentally allowed any property by falling back to "any"
customExpect(element).nonExistentProperty()

// @ts-expect-error
customExpect(element).toHaveClass(/cls/, {exact: true})
3 changes: 2 additions & 1 deletion types/matchers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,13 +249,14 @@ declare namespace matchers {
* const noClasses = getByTestId('no-classes')
* expect(deleteButton).toHaveClass('btn')
* expect(deleteButton).toHaveClass('btn-danger xs')
* expect(deleteButton).toHaveClass(/danger/, 'xs')
* expect(deleteButton).toHaveClass('btn xs btn-danger', {exact: true})
* expect(deleteButton).not.toHaveClass('btn xs btn-danger', {exact: true})
* expect(noClasses).not.toHaveClass()
* @see
* [testing-library/jest-dom#tohaveclass](https://github.com/testing-library/jest-dom#tohaveclass)
*/
toHaveClass(...classNames: string[]): R
toHaveClass(...classNames: Array<string | RegExp>): R
toHaveClass(classNames: string, options?: {exact: boolean}): R
/**
* @description
Expand Down
Loading