Skip to content

feat(native): Add toHaveTextContent matcher #153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: feat/native-to-have-style
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 84 additions & 2 deletions packages/native/src/lib/ElementAssertion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Assertion, AssertionError } from "@assertive-ts/core";
import { get } from "dot-prop-immutable";
import { ReactTestInstance } from "react-test-renderer";

import { instanceToString, isEmpty } from "./helpers/helpers";
import { instanceToString, isEmpty, testableTextMatcherToString, textMatches } from "./helpers/helpers";
import { getFlattenedStyle } from "./helpers/styles";
import { AssertiveStyle } from "./helpers/types";
import { AssertiveStyle, TestableTextMatcher, WithTextContent } from "./helpers/types";

export class ElementAssertion extends Assertion<ReactTestInstance> {
public constructor(actual: ReactTestInstance) {
Expand Down Expand Up @@ -243,6 +243,88 @@ export class ElementAssertion extends Assertion<ReactTestInstance> {
});
}

/**
* Check if the element has text content matching the provided string,
* RegExp, or function.
*
* @example
* ```
* expect(element).toHaveTextContent("Hello World");
* expect(element).toHaveTextContent(/Hello/);
* expect(element).toHaveTextContent(text => text.startsWith("Hello"));
* ```
*
* @param text - The text to check for.
* @returns the assertion instance
*/
public toHaveTextContent(text: TestableTextMatcher): this {
const actualTextContent = this.getTextContent(this.actual);
const matchesText = textMatches(actualTextContent, text);

const error = new AssertionError({
actual: this.actual,
message: `Expected element ${this.toString()} to have text content matching '` +
`${testableTextMatcherToString(text)}'.`,
});

const invertedError = new AssertionError({
actual: this.actual,
message:
`Expected element ${this.toString()} NOT to have text content matching '` +
`${testableTextMatcherToString(text)}'.`,
});

return this.execute({
assertWhen: matchesText,
error,
invertedError,
});
}

private getTextContent(element: ReactTestInstance): string {
if (!element) {
return "";
}

if (typeof element === "string") {
return element;
}

if (typeof element.props?.value === "string") {
return element.props.value;
}

return this.collectText(element).join(" ");
}

private collectText = (element: WithTextContent): string[] => {
if (typeof element === "string") {
return [element];
}

if (Array.isArray(element)) {
return element.flatMap(child => this.collectText(child));
}

if (element && typeof element === "object" && "props" in element) {
const value = element.props?.value as WithTextContent;
if (typeof value === "string") {
return [value];
}

const children = (element.props?.children as ReactTestInstance[]) ?? element.children;
if (!children) {
return [];
}

return Array.isArray(children)
? children.flatMap(this.collectText)
: this.collectText(children);
}

return [];
};

private isElementDisabled(element: ReactTestInstance): boolean {
const { type } = element;
const elementType = type.toString();
Expand Down
61 changes: 61 additions & 0 deletions packages/native/src/lib/helpers/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { ReactTestInstance } from "react-test-renderer";

import { TestableTextMatcher } from "./types";

/**
* Checks if a value is empty.
*
Expand Down Expand Up @@ -31,3 +33,62 @@ export function instanceToString(instance: ReactTestInstance | null): string {

return `<${instance.type.toString()} ... />`;
}

/**
* Converts a TestableTextMatcher to a string representation.
*
* @param matcher - The matcher to convert.
* @returns A string representation of the matcher.
* @throws Error if the matcher is not a string, RegExp, or function.
*/
export function testableTextMatcherToString(matcher: TestableTextMatcher): string {
if (typeof matcher === "string") {
return `String: "${matcher}"`;
}

if (matcher instanceof RegExp) {
return `RegExp: ${matcher.toString()}`;
}

if (typeof matcher === "function") {
return `Function: ${matcher.toString()}`;
}

throw new Error("Matcher must be a string, RegExp, or function.");
}

/**
* Checks if a text matches a given matcher.
*
* @param text - The text to check.
* @param matcher - The matcher to use for comparison.
* @returns `true` if the text matches the matcher, `false` otherwise.
* @throws Error if the matcher is not a string, RegExp, or function.
* @example
* ```ts
* textMatches("Hello World", "Hello World"); // true
* textMatches("Hello World", /Hello/); // true
* textMatches("Hello World", (text) => text.startsWith("Hello")); // true
* textMatches("Hello World", "Goodbye"); // false
* textMatches("Hello World", /Goodbye/); // false
* textMatches("Hello World", (text) => text.startsWith("Goodbye")); // false
* ```
*/
export function textMatches(
text: string,
matcher: TestableTextMatcher,
): boolean {
if (typeof matcher === "string") {
return text.includes(matcher);
}

if (matcher instanceof RegExp) {
return matcher.test(text);
}

if (typeof matcher === "function") {
return matcher(text);
}

throw new Error("Matcher must be a string, RegExp, or function.");
}
15 changes: 15 additions & 0 deletions packages/native/src/lib/helpers/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ImageStyle, StyleProp, TextStyle, ViewStyle } from "react-native";
import { ReactTestInstance } from "react-test-renderer";

/**
* Type representing a style that can be applied to a React Native component.
Expand All @@ -17,3 +18,17 @@ export type AssertiveStyle = StyleProp<Style>;
* It is a record where the keys are strings and the values can be of any type.
*/
export type StyleObject = Record<string, unknown>;

/**
* Type representing a matcher for text in tests.
*
* It can be a string, a regular expression, or a function that
* takes a string and returns a boolean.
*/
export type TestableTextMatcher = string | RegExp | ((text: string) => boolean);

/**
* Type representing a value that can be used to match text content in tests.
* It can be a string, a ReactTestInstance, or an array of ReactTestInstances.
*/
export type WithTextContent = string | ReactTestInstance | ReactTestInstance[];
179 changes: 179 additions & 0 deletions packages/native/test/lib/ElementAssertion.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -522,4 +522,183 @@ describe("[Unit] ElementAssertion.test.ts", () => {
});
});
});

describe(".toHaveTextContent", () => {
context("when the element contains the target text", () => {
it("returns the assertion instance", () => {
const element = render(
<Text testID="id">{"Hello World"}</Text>,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.toHaveTextContent("Hello World")).toBe(test);
expect(() => test.not.toHaveTextContent("Hello World"))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <Text ... /> NOT to have text content matching 'String: \"Hello World\"'.");
});
});

context("when the element does NOT contain the target text", () => {
it("throws an error", () => {
const element = render(
<Text testID="id">{"Hello World"}</Text>,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.not.toHaveTextContent("Goodbye World")).toBeEqual(test);
expect(() => test.toHaveTextContent("Goodbye World"))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <Text ... /> to have text content matching 'String: \"Goodbye World\"'.");
});
});

context("when the element contains the target text with a RegExp", () => {
it("returns the assertion instance", () => {
const element = render(
<Text testID="id">{"Hello World"}</Text>,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.toHaveTextContent(/Hello/)).toBe(test);
expect(() => test.not.toHaveTextContent(/Hello/))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <Text ... /> NOT to have text content matching 'RegExp: /Hello/'.");
});
});

context("when the element does NOT contain the target text with a RegExp", () => {
it("throws an error", () => {
const element = render(
<Text testID="id">{"Hello World"}</Text>,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.not.toHaveTextContent(/Goodbye/)).toBeEqual(test);
expect(() => test.toHaveTextContent(/Goodbye/))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <Text ... /> to have text content matching 'RegExp: /Goodbye/'.");
});
});

context("when the eleme contains the target text within a child element", () => {
it("returns the assertion instance", () => {
const element = render(
<View testID="id">
<View>
<Text>{"Test 1"}</Text>
<View>
<Text>{"Test 2"}</Text>
<Text>{"Hello World"}</Text>
</View>
</View>
</View>,
);
const test = new ElementAssertion(element.getByTestId("id"));
expect(test.toHaveTextContent("Hello World")).toBe(test);
expect(() => test.not.toHaveTextContent("Hello World"))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <View ... /> NOT to have text content matching 'String: \"Hello World\"'.");
});
});

context("when the element does NOT contain the target text within a child element", () => {
it("throws an error", () => {
const element = render(
<View testID="id">
<View>
<Text>{"Test 1"}</Text>
<View>
<Text>{"Test 2"}</Text>
<Text>{"Hello World"}</Text>
</View>
</View>
</View>,
);
const test = new ElementAssertion(element.getByTestId("id"));
expect(test.not.toHaveTextContent("Goodbye World")).toBeEqual(test);
expect(() => test.toHaveTextContent("Goodbye World"))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <View ... /> to have text content matching 'String: \"Goodbye World\"'.");
});
});

context("when the element contains the target text with a function matcher", () => {
it("returns the assertion instance", () => {
const element = render(
<Text testID="id">{"Hello World"}</Text>,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.toHaveTextContent(text => text.startsWith("Hello"))).toBe(test);
expect(() => test.not.toHaveTextContent(text => text.startsWith("Hello")))
.toThrowError(AssertionError)
.toHaveMessage(
"Expected element <Text ... /> NOT to have text content matching " +
"'Function: text => text.startsWith(\"Hello\")'.",
);
});
});

context("when the element does NOT contain the target text with a function matcher", () => {
it("throws an error", () => {
const element = render(
<Text testID="id">{"Hello World"}</Text>,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.not.toHaveTextContent(text => text.startsWith("Goodbye"))).toBeEqual(test);
expect(() => test.toHaveTextContent(text => text.startsWith("Goodbye")))
.toThrowError(AssertionError)
.toHaveMessage(
"Expected element <Text ... /> to have text content matching " +
"'Function: text => text.startsWith(\"Goodbye\")'.",
);
});
});

context("when the element has no text content", () => {
it("throws an error", () => {
const element = render(
<View testID="id" />,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.not.toHaveTextContent("Hello World")).toBeEqual(test);
expect(() => test.toHaveTextContent("Hello World"))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <View ... /> to have text content matching 'String: \"Hello World\"'.");
});
});

context("when the element has no text content with a RegExp", () => {
it("throws an error", () => {
const element = render(
<View testID="id" />,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.not.toHaveTextContent(/Hello/)).toBeEqual(test);
expect(() => test.toHaveTextContent(/Hello/))
.toThrowError(AssertionError)
.toHaveMessage("Expected element <View ... /> to have text content matching 'RegExp: /Hello/'.");
});
});

context("when the element has no text content with a function matcher", () => {
it("throws an error", () => {
const element = render(
<View testID="id" />,
);
const test = new ElementAssertion(element.getByTestId("id"));

expect(test.not.toHaveTextContent(text => text.startsWith("Hello"))).toBeEqual(test);
expect(() => test.toHaveTextContent(text => text.startsWith("Hello")))
.toThrowError(AssertionError)
.toHaveMessage(
"Expected element <View ... /> to have text content matching " +
"'Function: text => text.startsWith(\"Hello\")'.",
);
});
});
});
});