There are two similar methods that I want to refactor to eliminate redundant code. The first function returns a single element, while the second function returns multiple elements:
//returns a single element
const getByDataTest = (
container: HTMLElement,
dataTest: string
) => {
const element = queryByAttribute(
'data-test',
container,
dataTest
);
if (!element) {
throw queryHelpers.getElementError(
`Unable to find element by: [data-test="${dataTest}"]`,
container
);
}
return element;
};
//returns multiple elements
const getAllByDataTest = (
container: HTMLElement,
dataTest: string
) => {
const elements = queryAllByAttribute(
'data-test',
container,
dataTest
);
if (elements.length === 0) {
throw queryHelpers.getElementError(
`Unable to find any elements by: [data-test="${dataTest}"]`,
container
);
}
return elements;
};
To simplify this code, I aim to combine these functions into one by introducing a multiple
argument that toggles between using either of the query methods:
const getDataTest = (
container: HTMLElement,
dataTest: string,
multiple = false
) => {
//choose which query method to use
const queryMethod = multiple ? queryHelpers.queryAllByAttribute : queryHelpers.queryByAttribute;
const result = queryMethod(
'data-test',
container,
dataTest
);
if ((multiple && result.length === 0) || !result) {
throw queryHelpers.getElementError(
`Unable to find any element by: [data-test="${dataTest}"]`,
container
);
}
return result;
};
The issue arises when handling the result
variable of type HTMLElement | HTMLElement[]
, causing concerns with accessing result.length
. Various attempts have been made to address this error without success.