Skip to content

Commit

Permalink
fix: toHaveStyle assertion with invalid style (testing-library#564)
Browse files Browse the repository at this point in the history
Given an invalid declaration such as `fontSize: 8`, due to the missing
unit, the `toHaveStyle` matcher should not pass the following test:

```
render(<div data-testid="element" style={{ fontSize: 8 }} />)
expect(screen.getByTestId('element')).toHaveStyle({ fontSize: 1 })
```

This PR fixes testing-library#564 by adding a more restrictive guard in the matcher's
logic.
  • Loading branch information
EduardoSimon committed Feb 16, 2024
1 parent a93c0c4 commit c964341
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
9 changes: 9 additions & 0 deletions src/__tests__/to-have-style.js
Expand Up @@ -215,6 +215,15 @@ describe('.toHaveStyle', () => {
})
})

test('correctly matches invalid properties', () => {
const {queryByTestId} = render(`
<div data-testid="element" style="fontSize: 8" />
`)
expect(queryByTestId('element')).not.toHaveStyle({
fontSize: 1,
})
})

test('Fails with an invalid unit', () => {
const {queryByTestId} = render(`
<span data-testid="color-example" style="font-size: 12rem">Hello World</span>
Expand Down
21 changes: 17 additions & 4 deletions src/to-have-style.js
Expand Up @@ -14,6 +14,14 @@ function getStyleDeclaration(document, css) {
return styles
}

function isInvalidStyleDeclaration(name, value, computedStyle) {
return (
name &&
!value &&
!computedStyle[name] &&
!computedStyle.getPropertyValue(name)
)
}
function isSubset(styles, computedStyle) {
return (
!!Object.keys(styles).length &&
Expand All @@ -22,11 +30,16 @@ function isSubset(styles, computedStyle) {
const spellingVariants = [prop]
if (!isCustomProperty) spellingVariants.push(prop.toLowerCase())

return spellingVariants.some(
name =>
return spellingVariants.some(name => {
if (isInvalidStyleDeclaration(name, value, computedStyle)) {
return false
}

return (
computedStyle[name] === value ||
computedStyle.getPropertyValue(name) === value,
)
computedStyle.getPropertyValue(name) === value
)
})
})
)
}
Expand Down

0 comments on commit c964341

Please sign in to comment.