diff --git a/packages/dom/src/lib/ElementAssertion.ts b/packages/dom/src/lib/ElementAssertion.ts index 537d8084..ce14773c 100644 --- a/packages/dom/src/lib/ElementAssertion.ts +++ b/packages/dom/src/lib/ElementAssertion.ts @@ -1,4 +1,7 @@ import { Assertion, AssertionError } from "@assertive-ts/core"; +import equal from "fast-deep-equal"; + +import { getExpectedAndReceivedStyles } from "./helpers/helpers"; export class ElementAssertion extends Assertion { @@ -142,9 +145,42 @@ 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. + * + * @example + * ``` + * expect(component).toHaveStyle({ color: 'green', display: 'block' }); + * ``` + * + * @param expected the expected CSS styles. + * @returns the assertion instance. + */ + + public toHaveStyle(expected: Partial): this { + + const [expectedStyle, receivedStyle] = getExpectedAndReceivedStyles(this.actual, expected); + + if (!expectedStyle || !receivedStyle) { + throw new Error("Currently there are no available styles."); + } + + 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. @@ -181,4 +217,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 new file mode 100644 index 00000000..e8eaab87 --- /dev/null +++ b/packages/dom/src/lib/helpers/helpers.ts @@ -0,0 +1,75 @@ +interface StyleDeclaration extends Record { + property: string; + value: string; +} + +function normalizeStyles(css: Partial): StyleDeclaration { + const normalizer = document.createElement("div"); + document.body.appendChild(normalizer); + + const { expectedStyle } = Object.entries(css).reduce( + (acc, [property, value]) => { + + if (typeof value !== "string") { + return acc; + } + + normalizer.style.setProperty(property, value); + + const normalizedValue = window + .getComputedStyle(normalizer) + .getPropertyValue(property) + .trim(); + + return { + expectedStyle: { + ...acc.expectedStyle, + [property]: normalizedValue, + }, + }; + }, + { expectedStyle: {} as StyleDeclaration }, + ); + + document.body.removeChild(normalizer); + + return expectedStyle; +} + +function getReceivedStyle (props: string[], received: CSSStyleDeclaration): StyleDeclaration { + + return props.reduce((acc, prop) => { + + 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, + ]; +}; diff --git a/packages/dom/test/unit/lib/ElementAssertion.test.tsx b/packages/dom/test/unit/lib/ElementAssertion.test.tsx index 47bb1674..f91f10cd 100644 --- a/packages/dom/test/unit/lib/ElementAssertion.test.tsx +++ b/packages/dom/test/unit/lib/ElementAssertion.test.tsx @@ -257,12 +257,84 @@ 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); }); }); }); + describe(".toHaveStyle", () => { + 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("when 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(({ 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( +
, + ); + + const divTest = getByTestId("test-div"); + const test = new ElementAssertion(divTest); + + expect(() => test.toHaveStyle(({ color: "red", display: "flex" }))) + .toThrowError(AssertionError) + .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); + + }); + }); + }); });