From c964341c17692fde006bff9e5660edab174173e0 Mon Sep 17 00:00:00 2001 From: Eduardo Simon Date: Fri, 16 Feb 2024 23:35:20 +0100 Subject: [PATCH] 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 5991a7e..5d223af 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 010e2a5..68f670e 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 + ) + }) }) ) }