1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Introduce test helper to abstract discovery of HTML elements

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne Savolainen 2022-10-17 14:55:59 +03:00
parent cbfae0b6f5
commit 66dd1ab65e
No known key found for this signature in database
GPG Key ID: 8C6CFB2FFFE8F68A

View File

@ -0,0 +1,44 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { RenderResult } from "@testing-library/react";
export const querySingleElement =
(attributeName: string, attributeValue: string) =>
(rendered: RenderResult) => {
const dataAttribute = `data-${attributeName}-test`;
return rendered.baseElement.querySelector(
`[${dataAttribute}="${attributeValue}"]`,
);
};
export const queryAllElements =
(attributeName: string) => (rendered: RenderResult) => {
const dataAttribute = `data-${attributeName}-test`;
return [...rendered.baseElement.querySelectorAll(`[${dataAttribute}]`)];
};
export const getSingleElement =
(attributeName: string, attributeValue: string) =>
(rendered: RenderResult) => {
const dataAttribute = `data-${attributeName}-test`;
const element = querySingleElement(attributeName, attributeValue)(rendered);
if (!element) {
const validValues = queryAllElements(attributeName)(rendered).map(
(elem) => elem.getAttribute(dataAttribute),
);
throw new Error(
`Couldn't find HTML element with attribute "${dataAttribute}" with value "${attributeValue}". Valid values are:\n\n"${validValues.join(
'",\n"',
)}"`,
);
}
return element;
};