From 124a24bb5597e92ac6720b56ebe7ef3eb03e06c5 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 1 Aug 2025 14:04:57 -0500 Subject: [PATCH 01/14] Chore: added parse lib from adobe --- packages/dom/package.json | 1 + yarn.lock | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/packages/dom/package.json b/packages/dom/package.json index db420e8..cd59763 100644 --- a/packages/dom/package.json +++ b/packages/dom/package.json @@ -35,6 +35,7 @@ "test": "NODE_ENV=test mocha" }, "dependencies": { + "@adobe/css-tools": "^4.4.3", "fast-deep-equal": "^3.1.3", "tslib": "^2.6.2" }, diff --git a/yarn.lock b/yarn.lock index 12ff163..a2fc3e6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12,6 +12,13 @@ __metadata: languageName: node linkType: hard +"@adobe/css-tools@npm:^4.4.3": + version: 4.4.3 + resolution: "@adobe/css-tools@npm:4.4.3" + checksum: 10/701379c514b7a43ca6681705a93cd57ad79565cfef9591122e9499897550cf324a5e5bb1bc51df0e7433cf0e91b962c90f18ac459dcc98b2431daa04aa63cb20 + languageName: node + linkType: hard + "@ampproject/remapping@npm:^2.2.0": version: 2.2.1 resolution: "@ampproject/remapping@npm:2.2.1" @@ -49,6 +56,7 @@ __metadata: version: 0.0.0-use.local resolution: "@assertive-ts/dom@workspace:packages/dom" dependencies: + "@adobe/css-tools": "npm:^4.4.3" "@assertive-ts/core": "workspace:^" "@testing-library/dom": "npm:^10.1.0" "@testing-library/react": "npm:^16.0.0" From b032e7a1f0cf3ca49e82d306564d18180d22ea38 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 1 Aug 2025 14:07:51 -0500 Subject: [PATCH 02/14] Add: toHaveStyle first approach --- packages/dom/src/lib/ElementAssertion.ts | 72 ++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index bdbeb36..5669dfe 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -1,4 +1,5 @@ import { Assertion, AssertionError } from "@assertive-ts/core"; +import {parse} from '@adobe/css-tools' export class ElementAssertion extends Assertion { @@ -180,6 +181,77 @@ export class ElementAssertion extends Assertion { return this.actual.className.split(/\s+/).filter(Boolean); } + public toHaveStyle(css: Object|string): this { + const styleTest = document.createElement("div"); + styleTest.style.color = "red"; + styleTest.style.display = "flex"; + if ( + this.actual instanceof HTMLElement || + this.actual['ownerDocument'] + ) { + + + const parsedCSS = typeof css === 'object' + ? css + : parse(`selector { ${css} }`, {silent: true}).stylesheet + + const window = this.actual.ownerDocument.defaultView; + + const computedStyle = window?.getComputedStyle; + + const expected = parsedCSS + const received = computedStyle?.(this.actual); + console.log(received?.color); + const expectedRule = expected.rules[0]; + + interface StyleDeclaration { + property: string; + value: string; + } + + let style = {} + let props: string[] = [] + + expectedRule.declarations.map((declaration: StyleDeclaration) => { + const property = declaration.property; + const value = declaration.value; + + props = [...props, property]; + + style = { + ...style, + [property]: value, + }; + + return style + + }) + + console.log(style); + console.log(props); + + props.map((prop: string) => { + + console.log(received?.[prop]); + }) + + + return this.execute({ + assertWhen: true, + error: new AssertionError({ + actual: this.actual, + message: "Expected the element to have the specified style", + }), + invertedError: new AssertionError({ + actual: this.actual, + message: "Expected the element to NOT have the specified style", + }), + }); + } + return this; + } + + /** * Helper method to assert the presence or absence of class names. * From ab9906e649b592dd968daca405d57c1c2ec981b2 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 1 Aug 2025 14:08:16 -0500 Subject: [PATCH 03/14] Add: toHaveStyle tests first approach --- .../dom/test/unit/lib/ElementAssertion.test.tsx | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/dom/test/unit/lib/ElementAssertion.test.tsx b/packages/dom/test/unit/lib/ElementAssertion.test.tsx index 7b0f46c..e18b5b9 100644 --- a/packages/dom/test/unit/lib/ElementAssertion.test.tsx +++ b/packages/dom/test/unit/lib/ElementAssertion.test.tsx @@ -1,5 +1,5 @@ import { AssertionError, expect } from "@assertive-ts/core"; -import { render } from "@testing-library/react"; +import { getByTestId, render } from "@testing-library/react"; import { ElementAssertion } from "../../../src/lib/ElementAssertion"; @@ -296,4 +296,17 @@ describe("[Unit] ElementAssertion.test.ts", () => { }); }); }); + describe(".toHaveStyle", () => { + context("when the element has the expected style when passed as object", () => { + it("returns the assertion instance when it receives an object", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.toHaveStyle("display: flex; color: red")).toBeEqual(test); + + }); + }); +}); + }); From 1d35ec7f743fcd363854c79da59ed269f692ace2 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 8 Aug 2025 15:22:10 -0500 Subject: [PATCH 04/14] Refactor: toHaveStyle class --- packages/dom/src/lib/ElementAssertion.ts | 53 +++++++++++++++++------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index 5669dfe..f046c1b 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -201,7 +201,6 @@ export class ElementAssertion extends Assertion { const expected = parsedCSS const received = computedStyle?.(this.actual); - console.log(received?.color); const expectedRule = expected.rules[0]; interface StyleDeclaration { @@ -209,32 +208,58 @@ export class ElementAssertion extends Assertion { value: string; } - let style = {} + let expectedStyle = {} + let receivedStyle = {} let props: string[] = [] + const normalizer = document.createElement("div"); + document.body.appendChild(normalizer); + + expectedRule.declarations.map((declaration: StyleDeclaration) => { const property = declaration.property; const value = declaration.value; - + props = [...props, property]; - - style = { - ...style, - [property]: value, + + normalizer.style[property] = value; + const normalizedValue = window.getComputedStyle(normalizer).getPropertyValue(property); + + expectedStyle = { + ...expectedStyle, + [property]: normalizedValue.trim(), }; - - return style - }) + return expectedStyle; + }); + + document.body.removeChild(normalizer); - console.log(style); - console.log(props); + + console.log("expected style: ",expectedStyle); props.map((prop: string) => { - - console.log(received?.[prop]); + receivedStyle = { + ...receivedStyle, + [prop]: received?.getPropertyValue(prop).trim(), + }; }) + console.log("received style: ", receivedStyle); + + const isSameStyle = !!Object.keys(expectedStyle).length && + Object.entries(expectedStyle).every(([expectedProp, expectedValue]) => { + const isCustomProperty = expectedProp.startsWith('--') + const spellingVariants = [expectedProp] + expectedProp !== null; + + if (!isCustomProperty) spellingVariants.push(expectedProp.toLowerCase()) + return spellingVariants.some( searchProp => + receivedStyle[searchProp] === expectedValue + ) + }) + + console.log("isSameStyle: ", isSameStyle) return this.execute({ assertWhen: true, From 029ffd2d075ad2c399f8d4f9b8274db63c45d5b6 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 8 Aug 2025 15:22:53 -0500 Subject: [PATCH 05/14] Add: test for when styles are the same and the opposite case --- .../test/unit/lib/ElementAssertion.test.tsx | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/dom/test/unit/lib/ElementAssertion.test.tsx b/packages/dom/test/unit/lib/ElementAssertion.test.tsx index e18b5b9..d80ebaa 100644 --- a/packages/dom/test/unit/lib/ElementAssertion.test.tsx +++ b/packages/dom/test/unit/lib/ElementAssertion.test.tsx @@ -297,13 +297,38 @@ describe("[Unit] ElementAssertion.test.ts", () => { }); }); describe(".toHaveStyle", () => { + context("when the element has the expected style when passed as string", () => { + it("returns the assertion instance when the styles are the same", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.toHaveStyle("color: red; display: flex; border: 1px solid black")).toBeEqual(test); + + }); + it("fails the assertion when the styles are not the same", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.toHaveStyle("color: red; display: flex; border: 1px solid black;")).toBeEqual(test); + + }); context("when the element has the expected style when passed as object", () => { - it("returns the assertion instance when it receives an object", () => { + it("returns the assertion instance when the styles are the same", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})).toBeEqual(test); + + }); + it("fails the assertion when the styles are not the same", () => { const { getByTestId } = render(
); const divTest = getByTestId("test-div"); const test = new ElementAssertion(divTest); - expect(test.toHaveStyle("display: flex; color: red")).toBeEqual(test); + expect(test.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})).toBeEqual(test); }); }); From 1e1574cb3b5803bd515827e6f4482ca89c4df709 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Tue, 12 Aug 2025 10:33:02 -0500 Subject: [PATCH 06/14] Add: Funcionality for object cases --- packages/dom/src/lib/ElementAssertion.ts | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index f046c1b..8ae9f0e 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -182,14 +182,10 @@ export class ElementAssertion extends Assertion { } public toHaveStyle(css: Object|string): this { - const styleTest = document.createElement("div"); - styleTest.style.color = "red"; - styleTest.style.display = "flex"; if ( this.actual instanceof HTMLElement || this.actual['ownerDocument'] ) { - const parsedCSS = typeof css === 'object' ? css @@ -200,8 +196,8 @@ export class ElementAssertion extends Assertion { const computedStyle = window?.getComputedStyle; const expected = parsedCSS + console.log("expected: ", expected); const received = computedStyle?.(this.actual); - const expectedRule = expected.rules[0]; interface StyleDeclaration { property: string; @@ -215,7 +211,23 @@ export class ElementAssertion extends Assertion { const normalizer = document.createElement("div"); document.body.appendChild(normalizer); + if (typeof css === 'object') { + Object.entries(css).map(([property, value]) => { + props = [...props, property]; + + normalizer.style[property] = value; + const normalizedValue = window?.getComputedStyle(normalizer).getPropertyValue(property); + + expectedStyle = { + ...expectedStyle, + [property]: normalizedValue?.trim(), + }; + + }); + console.log("EXPECTED STYLE: ", expectedStyle); + } else { + const expectedRule = expected.rules[0]; expectedRule.declarations.map((declaration: StyleDeclaration) => { const property = declaration.property; const value = declaration.value; @@ -232,6 +244,7 @@ export class ElementAssertion extends Assertion { return expectedStyle; }); + } document.body.removeChild(normalizer); From 068c5199c03b32b02c6f4695648d6355e49bca70 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Tue, 12 Aug 2025 10:50:05 -0500 Subject: [PATCH 07/14] Add: Assertion execution --- packages/dom/src/lib/ElementAssertion.ts | 21 +++++++++++-------- .../test/unit/lib/ElementAssertion.test.tsx | 2 +- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index 8ae9f0e..fd6f5b8 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -273,17 +273,20 @@ export class ElementAssertion extends Assertion { }) console.log("isSameStyle: ", isSameStyle) - - return this.execute({ - assertWhen: true, - error: new AssertionError({ + const error = new AssertionError({ actual: this.actual, - message: "Expected the element to have the specified style", - }), - invertedError: new AssertionError({ + message: `Expected the element to have ${JSON.stringify(expectedStyle)} style`, + expected: expectedStyle + }) + const invertedError = new AssertionError({ actual: this.actual, - message: "Expected the element to NOT have the specified style", - }), + message: `Expected the element to NOT have ${JSON.stringify(expectedStyle)} style`, + }) + + return this.execute({ + assertWhen: isSameStyle, + error, + invertedError }); } return this; diff --git a/packages/dom/test/unit/lib/ElementAssertion.test.tsx b/packages/dom/test/unit/lib/ElementAssertion.test.tsx index d80ebaa..cdb6067 100644 --- a/packages/dom/test/unit/lib/ElementAssertion.test.tsx +++ b/packages/dom/test/unit/lib/ElementAssertion.test.tsx @@ -303,7 +303,7 @@ describe("[Unit] ElementAssertion.test.ts", () => { const divTest = getByTestId("test-div"); const test = new ElementAssertion(divTest); - expect(test.toHaveStyle("color: red; display: flex; border: 1px solid black")).toBeEqual(test); + expect(test.toHaveStyle("display: flex; color: red; border: 1px solid black")).toBeEqual(test); }); it("fails the assertion when the styles are not the same", () => { From 899a66984b6aa58f3be32ef417ba5d38135adc7f Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Wed, 27 Aug 2025 13:36:32 -0500 Subject: [PATCH 08/14] Add: functions moved into helpers and implemeneted in class --- packages/dom/src/lib/ElementAssertion.ts | 135 +++++++---------------- packages/dom/src/lib/helpers/helpers.ts | 100 +++++++++++++++++ 2 files changed, 137 insertions(+), 98 deletions(-) create mode 100644 packages/dom/src/lib/helpers/helpers.ts diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index fd6f5b8..4ab4465 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -1,5 +1,6 @@ import { Assertion, AssertionError } from "@assertive-ts/core"; -import {parse} from '@adobe/css-tools' +import { parse } from "@adobe/css-tools"; +import { CssAtRuleAST, getProps, isSameStyle, normalizeStylesObject, normalizeStylesString } from "./helpers/helpers"; export class ElementAssertion extends Assertion { @@ -181,112 +182,50 @@ export class ElementAssertion extends Assertion { return this.actual.className.split(/\s+/).filter(Boolean); } - public toHaveStyle(css: Object|string): this { - if ( - this.actual instanceof HTMLElement || - this.actual['ownerDocument'] - ) { - - const parsedCSS = typeof css === 'object' - ? css - : parse(`selector { ${css} }`, {silent: true}).stylesheet - - const window = this.actual.ownerDocument.defaultView; - - const computedStyle = window?.getComputedStyle; - - const expected = parsedCSS - console.log("expected: ", expected); - const received = computedStyle?.(this.actual); - - interface StyleDeclaration { - property: string; - value: string; - } - - let expectedStyle = {} - let receivedStyle = {} - let props: string[] = [] - - const normalizer = document.createElement("div"); - document.body.appendChild(normalizer); - - if (typeof css === 'object') { - Object.entries(css).map(([property, value]) => { - props = [...props, property]; - - normalizer.style[property] = value; - const normalizedValue = window?.getComputedStyle(normalizer).getPropertyValue(property); + /** + * Asserts that the element has the specified CSS styles. + * + * @param css - The expected CSS styles. + * @returns The assertion instance. + */ - expectedStyle = { - ...expectedStyle, - [property]: normalizedValue?.trim(), + public toHaveStyle(css: Object | string): this { + if (this.actual instanceof HTMLElement || this.actual["ownerDocument"]) { + const parsedCSS = + typeof css === "object" + ? css + : parse(`selector { ${css} }`, { silent: true }).stylesheet; - }; + const window = this.actual.ownerDocument.defaultView; + const computedStyle = window?.getComputedStyle; - }); - console.log("EXPECTED STYLE: ", expectedStyle); - } else { - const expectedRule = expected.rules[0]; - expectedRule.declarations.map((declaration: StyleDeclaration) => { - const property = declaration.property; - const value = declaration.value; + const expected = parsedCSS as CssAtRuleAST; + const received = computedStyle?.(this.actual) as CSSStyleDeclaration; - props = [...props, property]; - normalizer.style[property] = value; - const normalizedValue = window.getComputedStyle(normalizer).getPropertyValue(property); + const { props, expectedStyle } = + typeof css === "object" + ? normalizeStylesObject(css, window!) + : normalizeStylesString(expected, window!); - expectedStyle = { - ...expectedStyle, - [property]: normalizedValue.trim(), - }; - - return expectedStyle; - }); - } - - document.body.removeChild(normalizer); - - - console.log("expected style: ",expectedStyle); - - props.map((prop: string) => { - receivedStyle = { - ...receivedStyle, - [prop]: received?.getPropertyValue(prop).trim(), - }; - }) - - console.log("received style: ", receivedStyle); - - const isSameStyle = !!Object.keys(expectedStyle).length && - Object.entries(expectedStyle).every(([expectedProp, expectedValue]) => { - const isCustomProperty = expectedProp.startsWith('--') - const spellingVariants = [expectedProp] - expectedProp !== null; - - if (!isCustomProperty) spellingVariants.push(expectedProp.toLowerCase()) - return spellingVariants.some( searchProp => - receivedStyle[searchProp] === expectedValue - ) - }) - - console.log("isSameStyle: ", isSameStyle) - const error = new AssertionError({ - actual: this.actual, - message: `Expected the element to have ${JSON.stringify(expectedStyle)} style`, - expected: expectedStyle - }) - const invertedError = new AssertionError({ - actual: this.actual, - message: `Expected the element to NOT have ${JSON.stringify(expectedStyle)} style`, - }) + const receivedStyle = getProps(props, received); + const error = new AssertionError({ + actual: this.actual, + message: `Expected the element to have ${JSON.stringify(expectedStyle + )} style`, + expected: expectedStyle, + }); + const invertedError = new AssertionError({ + actual: this.actual, + message: `Expected the element to NOT have ${JSON.stringify( + expectedStyle + )} style`, + }); return this.execute({ - assertWhen: isSameStyle, + assertWhen: isSameStyle(expectedStyle, receivedStyle), error, - invertedError + invertedError, }); } return this; diff --git a/packages/dom/src/lib/helpers/helpers.ts b/packages/dom/src/lib/helpers/helpers.ts new file mode 100644 index 0000000..632ea62 --- /dev/null +++ b/packages/dom/src/lib/helpers/helpers.ts @@ -0,0 +1,100 @@ +export interface CssAtRuleAST { + rules: Rule[]; + declarations: StyleDeclaration[]; +} + +interface Rule { + selectors: string[]; + declarations: StyleDeclaration[]; +} + +interface StyleDeclaration extends Record { + property: string; + value: string; +} + +export const normalizeStylesObject = ( + css: Object, + window: Window +): { props: string[]; expectedStyle: StyleDeclaration } => { + const normalizer = document.createElement("div"); + document.body.appendChild(normalizer); + + const { props, expectedStyle } = Object.entries(css).reduce( + (acc, [property, value]) => { + normalizer.style.setProperty(property, value); + + const normalizedValue = window + .getComputedStyle(normalizer) + .getPropertyValue(property) + .trim(); + + return { + props: [...acc.props, property], + expectedStyle: { + ...acc.expectedStyle, + [property]: normalizedValue, + }, + }; + }, + { props: [] as string[], expectedStyle: {} as StyleDeclaration } + ); + + document.body.removeChild(normalizer); + + return { props, expectedStyle }; +}; + +export const normalizeStylesString = (expectedRule: CssAtRuleAST, window: Window) => { + const normalizer = document.createElement("div"); + document.body.appendChild(normalizer); + + const rules = expectedRule?.rules[0] || { declarations: [] }; + const { props, expectedStyle } = rules?.declarations.reduce( + (acc, { property, value }) => { + normalizer.style.setProperty(property, value); + + const normalizedValue = window + .getComputedStyle(normalizer) + .getPropertyValue(property) + .trim(); + + return { + props: [...acc.props, property], + expectedStyle: { + ...acc.expectedStyle, + [property]: normalizedValue, + }, + }; + }, + { props: [] as string[], expectedStyle: {} as StyleDeclaration } + ); + + document.body.removeChild(normalizer); + + return { props, expectedStyle }; +}; + +export const getProps = (props : string[], received: CSSStyleDeclaration) => { + return props.reduce((acc, prop) => { + acc[prop] = received?.getPropertyValue(prop).trim(); + return acc; + }, {} as StyleDeclaration); + +}; + +export const isSameStyle = (expectedStyle: StyleDeclaration, receivedStyle: StyleDeclaration): boolean => { + return !!Object.keys(expectedStyle).length && + Object.entries(expectedStyle).every(([expectedProp, expectedValue]) => { + const isCustomProperty = expectedProp.startsWith("--"); + const spellingVariants = [expectedProp]; + expectedProp !== null; + + if (!isCustomProperty) + spellingVariants.push(expectedProp.toLowerCase()); + return spellingVariants.some( + (searchProp) => receivedStyle[searchProp] === expectedValue + ); + }); +} + From 7384da620950f10a179fea17a9c45c6fcc6b6d9b Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Wed, 27 Aug 2025 13:37:18 -0500 Subject: [PATCH 09/14] Add: refactored test --- .../test/unit/lib/ElementAssertion.test.tsx | 90 +++++++++++-------- 1 file changed, 55 insertions(+), 35 deletions(-) diff --git a/packages/dom/test/unit/lib/ElementAssertion.test.tsx b/packages/dom/test/unit/lib/ElementAssertion.test.tsx index cdb6067..44fc4bb 100644 --- a/packages/dom/test/unit/lib/ElementAssertion.test.tsx +++ b/packages/dom/test/unit/lib/ElementAssertion.test.tsx @@ -1,5 +1,5 @@ import { AssertionError, expect } from "@assertive-ts/core"; -import { getByTestId, render } from "@testing-library/react"; +import { render } from "@testing-library/react"; import { ElementAssertion } from "../../../src/lib/ElementAssertion"; @@ -258,9 +258,9 @@ describe("[Unit] ElementAssertion.test.ts", () => { const test = new ElementAssertion(divTest); expect(() => test.toHaveAllClasses("foo", "bar", "baz")) - .toThrowError(AssertionError) - .toHaveMessage('Expected the element to have all of these classes: "foo bar baz"'); - + .toThrowError(AssertionError) + .toHaveMessage('Expected the element to have all of these classes: "foo bar baz"'); + expect(test.not.toHaveAllClasses("foo", "bar", "baz")).toBeEqual(test); }); }); @@ -297,41 +297,61 @@ describe("[Unit] ElementAssertion.test.ts", () => { }); }); describe(".toHaveStyle", () => { - context("when the element has the expected style when passed as string", () => { - it("returns the assertion instance when the styles are the same", () => { - const { getByTestId } = render(
); - const divTest = getByTestId("test-div"); - const test = new ElementAssertion(divTest); - - expect(test.toHaveStyle("display: flex; color: red; border: 1px solid black")).toBeEqual(test); - - }); - it("fails the assertion when the styles are not the same", () => { - const { getByTestId } = render(
); - const divTest = getByTestId("test-div"); - const test = new ElementAssertion(divTest); + context("when the style is passed as a string", () => { + context("and the element has the expected style", () => { + it("returns the assertion instance", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.toHaveStyle("display: flex; color: red; border: 1px solid black")).toBeEqual(test); + + expect(() => test.not.toHaveStyle("display: flex; color: red; border: 1px solid black")) + .toThrowError(AssertionError) + .toHaveMessage('Expected the element to NOT have {"display":"flex","color":"rgb(255, 0, 0)","border":"1px solid black"} style'); + }); + }); - expect(test.toHaveStyle("color: red; display: flex; border: 1px solid black;")).toBeEqual(test); + context("and the element does not have the expected style", () => { + it("throws an assertion error", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.not.toHaveStyle("color: red; display: flex; border: 1px solid black;")).toBeEqual(test); + }); + }); }); - context("when the element has the expected style when passed as object", () => { - it("returns the assertion instance when the styles are the same", () => { - const { getByTestId } = render(
); - const divTest = getByTestId("test-div"); - const test = new ElementAssertion(divTest); - - expect(test.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})).toBeEqual(test); - }); - it("fails the assertion when the styles are not the same", () => { - const { getByTestId } = render(
); - const divTest = getByTestId("test-div"); - const test = new ElementAssertion(divTest); + context("when the style is passed as an object", () => { + context("and the element has the expected style", () => { + it("returns the assertion instance", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})).toBeEqual(test); - expect(test.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})).toBeEqual(test); + expect(() => test.not.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})) + .toThrowError(AssertionError) + .toHaveMessage('Expected the element to NOT have {"color":"rgb(255, 0, 0)","display":"flex","border":"1px solid black"} style'); + + }); + }); - }); + context("and the element does not have the expected style", () => { + it("throws an assertion error", () => { + const { getByTestId } = render(
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(() => test.toHaveStyle(({ color: "red", display: "flex", border: "1px solid black" }))) + .toThrowError(AssertionError) + .toHaveMessage("Expected the element to have {\"color\":\"rgb(255, 0, 0)\",\"display\":\"flex\",\"border\":\"1px solid black\"} style"); + + }); + }); + }); }); -}); - -}); +}) From 469d40f6410cff617bfe726f3db8e757f9dee178 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Mon, 1 Sep 2025 15:36:31 -0500 Subject: [PATCH 10/14] Add: simplified logic and refactored functions --- packages/dom/src/lib/ElementAssertion.ts | 81 +++++++++++------------- packages/dom/src/lib/helpers/helpers.ts | 70 ++++---------------- 2 files changed, 51 insertions(+), 100 deletions(-) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index 4ab4465..5229f6e 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -1,6 +1,7 @@ import { Assertion, AssertionError } from "@assertive-ts/core"; -import { parse } from "@adobe/css-tools"; -import { CssAtRuleAST, getProps, isSameStyle, normalizeStylesObject, normalizeStylesString } from "./helpers/helpers"; +import equal from "fast-deep-equal"; + +import { getReceivedStyle, normalizeStyles } from "./helpers/helpers"; export class ElementAssertion extends Assertion { @@ -185,52 +186,42 @@ export class ElementAssertion extends Assertion { /** * Asserts that the element has the specified CSS styles. * - * @param css - The expected CSS styles. + * @param expected - The expected CSS styles. * @returns The assertion instance. */ - public toHaveStyle(css: Object | string): this { - if (this.actual instanceof HTMLElement || this.actual["ownerDocument"]) { - const parsedCSS = - typeof css === "object" - ? css - : parse(`selector { ${css} }`, { silent: true }).stylesheet; - - const window = this.actual.ownerDocument.defaultView; - const computedStyle = window?.getComputedStyle; - - const expected = parsedCSS as CssAtRuleAST; - const received = computedStyle?.(this.actual) as CSSStyleDeclaration; - - - const { props, expectedStyle } = - typeof css === "object" - ? normalizeStylesObject(css, window!) - : normalizeStylesString(expected, window!); - - const receivedStyle = getProps(props, received); - - const error = new AssertionError({ - actual: this.actual, - message: `Expected the element to have ${JSON.stringify(expectedStyle - )} style`, - expected: expectedStyle, - }); - const invertedError = new AssertionError({ - actual: this.actual, - message: `Expected the element to NOT have ${JSON.stringify( - expectedStyle - )} style`, - }); - return this.execute({ - assertWhen: isSameStyle(expectedStyle, receivedStyle), - error, - invertedError, - }); + public toHaveStyle(expected: Partial): this { + if (!this.actual.ownerDocument.defaultView) { + throw new Error("The element is not attached to a document with a default view."); } - return this; - } + if (!(this.actual instanceof HTMLElement)) { + throw new Error("The element is not an HTMLElement."); + } + + const window = this.actual.ownerDocument.defaultView; + + const received = window.getComputedStyle(this.actual); + + const { props, expectedStyle } = normalizeStyles(expected); + const receivedStyle = getReceivedStyle(props, received); + + const error = new AssertionError({ + actual: this.actual, + expected: expectedStyle, + message: `Expected the element to match the following style:\n${JSON.stringify(expectedStyle, null, 2)}`, + }); + const invertedError = new AssertionError({ + actual: this.actual, + message: `Expected the element to NOT match the following style:\n${JSON.stringify(expectedStyle, null, 2)}`, + }); + + return this.execute({ + assertWhen: equal(expectedStyle, receivedStyle), + error, + invertedError, + }); + } /** * Helper method to assert the presence or absence of class names. @@ -267,4 +258,8 @@ export class ElementAssertion extends Assertion { invertedError, }); } + + private getClassList(): string[] { + return this.actual.className.split(/\s+/).filter(Boolean); + } } diff --git a/packages/dom/src/lib/helpers/helpers.ts b/packages/dom/src/lib/helpers/helpers.ts index 632ea62..843be7d 100644 --- a/packages/dom/src/lib/helpers/helpers.ts +++ b/packages/dom/src/lib/helpers/helpers.ts @@ -1,11 +1,11 @@ export interface CssAtRuleAST { - rules: Rule[]; declarations: StyleDeclaration[]; + rules: Rule[]; } interface Rule { - selectors: string[]; declarations: StyleDeclaration[]; + selectors: string[]; } interface StyleDeclaration extends Record { @@ -13,15 +13,18 @@ interface StyleDeclaration extends Record { value: string; } -export const normalizeStylesObject = ( - css: Object, - window: Window -): { props: string[]; expectedStyle: StyleDeclaration } => { +export const normalizeStyles = (css: Partial): +{ expectedStyle: StyleDeclaration; props: string[]; } => { const normalizer = document.createElement("div"); document.body.appendChild(normalizer); const { props, expectedStyle } = Object.entries(css).reduce( (acc, [property, value]) => { + + if (typeof value !== "string") { + return acc; + } + normalizer.style.setProperty(property, value); const normalizedValue = window @@ -30,71 +33,24 @@ export const normalizeStylesObject = ( .trim(); return { - props: [...acc.props, property], expectedStyle: { ...acc.expectedStyle, [property]: normalizedValue, }, + props: [...acc.props, property], }; }, - { props: [] as string[], expectedStyle: {} as StyleDeclaration } + { expectedStyle: {} as StyleDeclaration, props: [] as string[] }, ); document.body.removeChild(normalizer); - return { props, expectedStyle }; -}; - -export const normalizeStylesString = (expectedRule: CssAtRuleAST, window: Window) => { - const normalizer = document.createElement("div"); - document.body.appendChild(normalizer); - - const rules = expectedRule?.rules[0] || { declarations: [] }; - const { props, expectedStyle } = rules?.declarations.reduce( - (acc, { property, value }) => { - normalizer.style.setProperty(property, value); - - const normalizedValue = window - .getComputedStyle(normalizer) - .getPropertyValue(property) - .trim(); - - return { - props: [...acc.props, property], - expectedStyle: { - ...acc.expectedStyle, - [property]: normalizedValue, - }, - }; - }, - { props: [] as string[], expectedStyle: {} as StyleDeclaration } - ); - - document.body.removeChild(normalizer); - - return { props, expectedStyle }; + return { expectedStyle, props }; }; -export const getProps = (props : string[], received: CSSStyleDeclaration) => { +export const getReceivedStyle = (props: string[], received: CSSStyleDeclaration): StyleDeclaration => { return props.reduce((acc, prop) => { acc[prop] = received?.getPropertyValue(prop).trim(); return acc; }, {} as StyleDeclaration); - }; - -export const isSameStyle = (expectedStyle: StyleDeclaration, receivedStyle: StyleDeclaration): boolean => { - return !!Object.keys(expectedStyle).length && - Object.entries(expectedStyle).every(([expectedProp, expectedValue]) => { - const isCustomProperty = expectedProp.startsWith("--"); - const spellingVariants = [expectedProp]; - expectedProp !== null; - - if (!isCustomProperty) - spellingVariants.push(expectedProp.toLowerCase()); - return spellingVariants.some( - (searchProp) => receivedStyle[searchProp] === expectedValue - ); - }); -} - From 38a575ca414b5009eaa9d308337db907afc566de Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 3 Oct 2025 12:03:37 -0500 Subject: [PATCH 11/14] Add: test for partial match --- packages/dom/src/lib/ElementAssertion.ts | 9 +- .../test/unit/lib/ElementAssertion.test.tsx | 100 ++++++++++-------- 2 files changed, 64 insertions(+), 45 deletions(-) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index 5229f6e..3a78083 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -186,8 +186,13 @@ export class ElementAssertion extends Assertion { /** * Asserts that the element has the specified CSS styles. * - * @param expected - The expected CSS styles. - * @returns The assertion instance. + * @example + * ``` + * expect(component).toHaveStyle({ color: 'green', display: 'block' }); + * ``` + * + * @param expected the expected CSS styles. + * @returns the assertion instance. */ public toHaveStyle(expected: Partial): this { diff --git a/packages/dom/test/unit/lib/ElementAssertion.test.tsx b/packages/dom/test/unit/lib/ElementAssertion.test.tsx index 44fc4bb..1a77fe2 100644 --- a/packages/dom/test/unit/lib/ElementAssertion.test.tsx +++ b/packages/dom/test/unit/lib/ElementAssertion.test.tsx @@ -260,7 +260,7 @@ describe("[Unit] ElementAssertion.test.ts", () => { expect(() => test.toHaveAllClasses("foo", "bar", "baz")) .toThrowError(AssertionError) .toHaveMessage('Expected the element to have all of these classes: "foo bar baz"'); - + expect(test.not.toHaveAllClasses("foo", "bar", "baz")).toBeEqual(test); }); }); @@ -297,61 +297,75 @@ describe("[Unit] ElementAssertion.test.ts", () => { }); }); describe(".toHaveStyle", () => { - context("when the style is passed as a string", () => { - context("and the element has the expected style", () => { - it("returns the assertion instance", () => { - const { getByTestId } = render(
); - const divTest = getByTestId("test-div"); - const test = new ElementAssertion(divTest); - - expect(test.toHaveStyle("display: flex; color: red; border: 1px solid black")).toBeEqual(test); - - expect(() => test.not.toHaveStyle("display: flex; color: red; border: 1px solid black")) - .toThrowError(AssertionError) - .toHaveMessage('Expected the element to NOT have {"display":"flex","color":"rgb(255, 0, 0)","border":"1px solid black"} style'); - }); + context("when the element has the expected style", () => { + it("returns the assertion instance", () => { + const { getByTestId } = render( +
); + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(test.toHaveStyle({ border: "1px solid black", color: "red", display: "flex" })).toBeEqual(test); + + expect(() => test.not.toHaveStyle({ border: "1px solid black", color: "red", display: "flex" })) + .toThrowError(AssertionError) + .toHaveMessage( + // eslint-disable-next-line max-len + 'Expected the element to NOT match the following style:\n{\n "border": "1px solid black",\n "color": "rgb(255, 0, 0)",\n "display": "flex"\n}', + ); }); + }); - context("and the element does not have the expected style", () => { + context("when the element does not have the expected style", () => { it("throws an assertion error", () => { - const { getByTestId } = render(
); + const { getByTestId } = render( +
, + ); + const divTest = getByTestId("test-div"); const test = new ElementAssertion(divTest); - - expect(test.not.toHaveStyle("color: red; display: flex; border: 1px solid black;")).toBeEqual(test); + + expect(() => test.toHaveStyle(({ border: "1px solid black", color: "red", display: "flex" }))) + .toThrowError(AssertionError) + .toHaveMessage( + // eslint-disable-next-line max-len + 'Expected the element to match the following style:\n{\n "border": "1px solid black",\n "color": "rgb(255, 0, 0)",\n "display": "flex"\n}', + ); + + expect(test.not.toHaveStyle({ border: "1px solid black", color: "red", display: "flex" })).toBeEqual(test); }); - }); }); + context("when the element partially match the style", () => { + it("throws an assertion error", () => { + const { getByTestId } = render( +
, + ); - context("when the style is passed as an object", () => { - context("and the element has the expected style", () => { - it("returns the assertion instance", () => { - const { getByTestId } = render(
); const divTest = getByTestId("test-div"); const test = new ElementAssertion(divTest); - - expect(test.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})).toBeEqual(test); - expect(() => test.not.toHaveStyle({color: "red", display: "flex", border: "1px solid black"})) + expect(() => test.toHaveStyle(({ color: "red", display: "flex" }))) .toThrowError(AssertionError) - .toHaveMessage('Expected the element to NOT have {"color":"rgb(255, 0, 0)","display":"flex","border":"1px solid black"} style'); - - }); - }); + .toHaveMessage( + // eslint-disable-next-line max-len + 'Expected the element to match the following style:\n{\n "color": "rgb(255, 0, 0)",\n "display": "flex"\n}', + ); + + expect(test.not.toHaveStyle({ border: "1px solid black", color: "red", display: "flex" })).toBeEqual(test); - context("and the element does not have the expected style", () => { - it("throws an assertion error", () => { - const { getByTestId } = render(
); - const divTest = getByTestId("test-div"); - const test = new ElementAssertion(divTest); - - expect(() => test.toHaveStyle(({ color: "red", display: "flex", border: "1px solid black" }))) - .toThrowError(AssertionError) - .toHaveMessage("Expected the element to have {\"color\":\"rgb(255, 0, 0)\",\"display\":\"flex\",\"border\":\"1px solid black\"} style"); - - }); }); - }); + }); }); -}) +}); From 03d88877a90c9b1565ca8dd7de42b2fba5b54aa6 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 19 Dec 2025 12:49:17 -0500 Subject: [PATCH 12/14] refactor: logic improved --- packages/dom/src/lib/ElementAssertion.ts | 18 ++------ packages/dom/src/lib/helpers/helpers.ts | 59 ++++++++++++++++-------- 2 files changed, 44 insertions(+), 33 deletions(-) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index 3a78083..5806312 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -1,7 +1,7 @@ import { Assertion, AssertionError } from "@assertive-ts/core"; import equal from "fast-deep-equal"; -import { getReceivedStyle, normalizeStyles } from "./helpers/helpers"; +import { getExpectedAndReceivedStyles } from "./helpers/helpers"; export class ElementAssertion extends Assertion { @@ -196,20 +196,12 @@ export class ElementAssertion extends Assertion { */ public toHaveStyle(expected: Partial): this { - if (!this.actual.ownerDocument.defaultView) { - throw new Error("The element is not attached to a document with a default view."); - } - if (!(this.actual instanceof HTMLElement)) { - throw new Error("The element is not an HTMLElement."); - } - - const window = this.actual.ownerDocument.defaultView; - const received = window.getComputedStyle(this.actual); + const [expectedStyle, receivedStyle] = getExpectedAndReceivedStyles(this.actual, expected); - const { props, expectedStyle } = normalizeStyles(expected); - - const receivedStyle = getReceivedStyle(props, received); + if (!expectedStyle || !receivedStyle) { + throw new Error("Currently there are no available styles."); + } const error = new AssertionError({ actual: this.actual, diff --git a/packages/dom/src/lib/helpers/helpers.ts b/packages/dom/src/lib/helpers/helpers.ts index 843be7d..e8eaab8 100644 --- a/packages/dom/src/lib/helpers/helpers.ts +++ b/packages/dom/src/lib/helpers/helpers.ts @@ -1,24 +1,13 @@ -export interface CssAtRuleAST { - declarations: StyleDeclaration[]; - rules: Rule[]; -} - -interface Rule { - declarations: StyleDeclaration[]; - selectors: string[]; -} - interface StyleDeclaration extends Record { property: string; value: string; } -export const normalizeStyles = (css: Partial): -{ expectedStyle: StyleDeclaration; props: string[]; } => { +function normalizeStyles(css: Partial): StyleDeclaration { const normalizer = document.createElement("div"); document.body.appendChild(normalizer); - const { props, expectedStyle } = Object.entries(css).reduce( + const { expectedStyle } = Object.entries(css).reduce( (acc, [property, value]) => { if (typeof value !== "string") { @@ -37,20 +26,50 @@ export const normalizeStyles = (css: Partial): ...acc.expectedStyle, [property]: normalizedValue, }, - props: [...acc.props, property], }; }, - { expectedStyle: {} as StyleDeclaration, props: [] as string[] }, + { expectedStyle: {} as StyleDeclaration }, ); document.body.removeChild(normalizer); - return { expectedStyle, props }; -}; + return expectedStyle; +} + +function getReceivedStyle (props: string[], received: CSSStyleDeclaration): StyleDeclaration { -export const getReceivedStyle = (props: string[], received: CSSStyleDeclaration): StyleDeclaration => { return props.reduce((acc, prop) => { - acc[prop] = received?.getPropertyValue(prop).trim(); - return acc; + + const actualStyle = received.getPropertyValue(prop).trim(); + + return actualStyle + ? { ...acc, [prop]: actualStyle } + : acc; + }, {} as StyleDeclaration); +} + +export const getExpectedAndReceivedStyles = +(actual: Element, expected: Partial): StyleDeclaration[] => { + if (!actual.ownerDocument.defaultView) { + throw new Error("The element is not attached to a document with a default view."); + } + if (!(actual instanceof HTMLElement)) { + throw new Error("The element is not an HTMLElement."); + } + + const window = actual.ownerDocument.defaultView; + + const rawElementStyles = window.getComputedStyle(actual); + + const expectedStyle = normalizeStyles(expected); + + const styleKeys = Object.keys(expectedStyle); + + const elementProcessedStyle = getReceivedStyle(styleKeys, rawElementStyles); + + return [ + expectedStyle, + elementProcessedStyle, + ]; }; From 8b2bdb70b80dde04e6b1963de1fe30ceb03845d1 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Fri, 19 Dec 2025 12:49:51 -0500 Subject: [PATCH 13/14] chore: removed @adobe/css-tools since it's not longer used --- packages/dom/package.json | 1 - yarn.lock | 8 -------- 2 files changed, 9 deletions(-) diff --git a/packages/dom/package.json b/packages/dom/package.json index cd59763..db420e8 100644 --- a/packages/dom/package.json +++ b/packages/dom/package.json @@ -35,7 +35,6 @@ "test": "NODE_ENV=test mocha" }, "dependencies": { - "@adobe/css-tools": "^4.4.3", "fast-deep-equal": "^3.1.3", "tslib": "^2.6.2" }, diff --git a/yarn.lock b/yarn.lock index a2fc3e6..12ff163 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12,13 +12,6 @@ __metadata: languageName: node linkType: hard -"@adobe/css-tools@npm:^4.4.3": - version: 4.4.3 - resolution: "@adobe/css-tools@npm:4.4.3" - checksum: 10/701379c514b7a43ca6681705a93cd57ad79565cfef9591122e9499897550cf324a5e5bb1bc51df0e7433cf0e91b962c90f18ac459dcc98b2431daa04aa63cb20 - languageName: node - linkType: hard - "@ampproject/remapping@npm:^2.2.0": version: 2.2.1 resolution: "@ampproject/remapping@npm:2.2.1" @@ -56,7 +49,6 @@ __metadata: version: 0.0.0-use.local resolution: "@assertive-ts/dom@workspace:packages/dom" dependencies: - "@adobe/css-tools": "npm:^4.4.3" "@assertive-ts/core": "workspace:^" "@testing-library/dom": "npm:^10.1.0" "@testing-library/react": "npm:^16.0.0" From eaec50a8a51ccd06989515e8f7f10993e194d6f5 Mon Sep 17 00:00:00 2001 From: Sebas Cruz Date: Tue, 30 Dec 2025 11:37:00 -0500 Subject: [PATCH 14/14] Chore: cleaning up duplicated function after conflict solving --- packages/dom/src/lib/ElementAssertion.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index 5806312..2ae9b29 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -179,10 +179,6 @@ export class ElementAssertion extends Assertion { }); } - private getClassList(): string[] { - return this.actual.className.split(/\s+/).filter(Boolean); - } - /** * Asserts that the element has the specified CSS styles. *