From fd3089f0844d291684679cb1d67084cabdf4a84b Mon Sep 17 00:00:00 2001 From: Eduardo Simon Date: Fri, 16 Feb 2024 23:35:20 +0100 Subject: [PATCH 1/2] fix: toHaveStyle assertion with invalid style (#564) Given an invalid declaration such as `fontSize: 8`, due to the missing unit, the `toHaveStyle` matcher should not pass the following test: ``` render(
) expect(screen.getByTestId('element')).toHaveStyle({ fontSize: 1 }) ``` This PR fixes #564 by adding a more restrictive guard in the matcher's logic. --- src/__tests__/to-have-style.js | 9 +++++++++ src/to-have-style.js | 21 +++++++++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/__tests__/to-have-style.js b/src/__tests__/to-have-style.js index 5991a7e9..5d223af4 100644 --- a/src/__tests__/to-have-style.js +++ b/src/__tests__/to-have-style.js @@ -215,6 +215,15 @@ describe('.toHaveStyle', () => { }) }) + test('correctly matches invalid properties', () => { + const {queryByTestId} = render(` +
+ `) + expect(queryByTestId('element')).not.toHaveStyle({ + fontSize: 1, + }) + }) + test('Fails with an invalid unit', () => { const {queryByTestId} = render(` Hello World diff --git a/src/to-have-style.js b/src/to-have-style.js index 010e2a5d..68f670e2 100644 --- a/src/to-have-style.js +++ b/src/to-have-style.js @@ -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 && @@ -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 + ) + }) }) ) } From fc7d9b70045e4cdd77a20bf8134e259508e8d879 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eduardo=20Sim=C3=B3n=20Pic=C3=B3n?= Date: Sat, 12 Oct 2024 12:34:13 +0200 Subject: [PATCH 2/2] chore: style suggestion applied MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ernesto GarcĂ­a --- src/to-have-style.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/to-have-style.js b/src/to-have-style.js index 68f670e2..f39a25cd 100644 --- a/src/to-have-style.js +++ b/src/to-have-style.js @@ -22,6 +22,7 @@ function isInvalidStyleDeclaration(name, value, computedStyle) { !computedStyle.getPropertyValue(name) ) } + function isSubset(styles, computedStyle) { return ( !!Object.keys(styles).length &&