From b7b7c6a9652f259434d13a22e4319826a4bd4d8b Mon Sep 17 00:00:00 2001 From: Paolo Priotto Date: Thu, 30 Nov 2023 20:37:14 +0100 Subject: [PATCH] fix: support uppercase custom props in toHaveStyle (#552) --- src/__tests__/to-have-style.js | 16 +++++++++++----- src/to-have-style.js | 16 +++++++++++----- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/__tests__/to-have-style.js b/src/__tests__/to-have-style.js index 0d94efaa..5991a7e9 100644 --- a/src/__tests__/to-have-style.js +++ b/src/__tests__/to-have-style.js @@ -70,6 +70,7 @@ describe('.toHaveStyle', () => { background-color: black; color: white; float: left; + --var-name: 0px; transition: opacity 0.2s ease-out, top 0.3s cubic-bezier(1.175, 0.885, 0.32, 1.275); } ` @@ -92,6 +93,11 @@ describe('.toHaveStyle', () => { ), ).toThrowError() + // Custom property names are case sensitive + expect(() => + expect(container.querySelector('.label')).toHaveStyle('--VAR-NAME: 0px;'), + ).toThrowError() + // Make sure the test fails if the css syntax is not valid expect(() => expect(container.querySelector('.label')).not.toHaveStyle( @@ -119,11 +125,11 @@ describe('.toHaveStyle', () => { ) }) - test('handles inline custom properties', () => { + test('handles inline custom properties (with uppercase letters)', () => { const {queryByTestId} = render(` - Hello World + Hello World `) - expect(queryByTestId('color-example')).toHaveStyle('--color: blue') + expect(queryByTestId('color-example')).toHaveStyle('--accentColor: blue') }) test('handles global custom properties', () => { @@ -205,7 +211,7 @@ describe('.toHaveStyle', () => { Hello World `) expect(queryByTestId('color-example')).toHaveStyle({ - fontSize: 12 + fontSize: 12, }) }) @@ -214,7 +220,7 @@ describe('.toHaveStyle', () => { Hello World `) expect(() => { - expect(queryByTestId('color-example')).toHaveStyle({ fontSize: '12px' }) + expect(queryByTestId('color-example')).toHaveStyle({fontSize: '12px'}) }).toThrowError() }) diff --git a/src/to-have-style.js b/src/to-have-style.js index f125450c..010e2a5d 100644 --- a/src/to-have-style.js +++ b/src/to-have-style.js @@ -17,11 +17,17 @@ function getStyleDeclaration(document, css) { function isSubset(styles, computedStyle) { return ( !!Object.keys(styles).length && - Object.entries(styles).every( - ([prop, value]) => - computedStyle[prop] === value || - computedStyle.getPropertyValue(prop.toLowerCase()) === value, - ) + Object.entries(styles).every(([prop, value]) => { + const isCustomProperty = prop.startsWith('--') + const spellingVariants = [prop] + if (!isCustomProperty) spellingVariants.push(prop.toLowerCase()) + + return spellingVariants.some( + name => + computedStyle[name] === value || + computedStyle.getPropertyValue(name) === value, + ) + }) ) }