Skip to content

Commit c964341

Browse files
committed
fix: toHaveStyle assertion with invalid style (testing-library#564)
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.
1 parent a93c0c4 commit c964341

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

Diff for: src/__tests__/to-have-style.js

+9
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,15 @@ describe('.toHaveStyle', () => {
215215
})
216216
})
217217

218+
test('correctly matches invalid properties', () => {
219+
const {queryByTestId} = render(`
220+
<div data-testid="element" style="fontSize: 8" />
221+
`)
222+
expect(queryByTestId('element')).not.toHaveStyle({
223+
fontSize: 1,
224+
})
225+
})
226+
218227
test('Fails with an invalid unit', () => {
219228
const {queryByTestId} = render(`
220229
<span data-testid="color-example" style="font-size: 12rem">Hello World</span>

Diff for: src/to-have-style.js

+17-4
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ function getStyleDeclaration(document, css) {
1414
return styles
1515
}
1616

17+
function isInvalidStyleDeclaration(name, value, computedStyle) {
18+
return (
19+
name &&
20+
!value &&
21+
!computedStyle[name] &&
22+
!computedStyle.getPropertyValue(name)
23+
)
24+
}
1725
function isSubset(styles, computedStyle) {
1826
return (
1927
!!Object.keys(styles).length &&
@@ -22,11 +30,16 @@ function isSubset(styles, computedStyle) {
2230
const spellingVariants = [prop]
2331
if (!isCustomProperty) spellingVariants.push(prop.toLowerCase())
2432

25-
return spellingVariants.some(
26-
name =>
33+
return spellingVariants.some(name => {
34+
if (isInvalidStyleDeclaration(name, value, computedStyle)) {
35+
return false
36+
}
37+
38+
return (
2739
computedStyle[name] === value ||
28-
computedStyle.getPropertyValue(name) === value,
29-
)
40+
computedStyle.getPropertyValue(name) === value
41+
)
42+
})
3043
})
3144
)
3245
}

0 commit comments

Comments
 (0)