diff options
| author | Tobias Järvelöv <tobias.jarvelov@mullvad.net> | 2025-10-24 11:15:20 +0200 |
|---|---|---|
| committer | Tobias Järvelöv <tobias.jarvelov@mullvad.net> | 2025-10-27 15:36:50 +0100 |
| commit | 51fdf7174e893b980f72929e55c7013430cd7f57 (patch) | |
| tree | 259dc5b110afe52c70d1d33ecc5aa1d17a614628 | |
| parent | 9aec65e3fb0abc49d35baeeaed7e4bb1caa57e93 (diff) | |
| download | mullvadvpn-51fdf7174e893b980f72929e55c7013430cd7f57.tar.xz mullvadvpn-51fdf7174e893b980f72929e55c7013430cd7f57.zip | |
Refactor expectChildrenToMatch to remove need for type casting
| -rw-r--r-- | desktop/packages/mullvad-vpn/test/unit/utils.ts | 34 |
1 files changed, 27 insertions, 7 deletions
diff --git a/desktop/packages/mullvad-vpn/test/unit/utils.ts b/desktop/packages/mullvad-vpn/test/unit/utils.ts index b69c2387a1..715bcfe03c 100644 --- a/desktop/packages/mullvad-vpn/test/unit/utils.ts +++ b/desktop/packages/mullvad-vpn/test/unit/utils.ts @@ -1,13 +1,33 @@ import { expect } from 'chai'; import React from 'react'; -type WithChildren = React.ReactElement<{ children?: React.ReactNode }>; +type ReactElementWithChildren = React.ReactElement<{ children: React.ReactNode }>; -export const expectChildrenToMatch = (element: React.ReactElement, expectedParts: string[]) => { - const kids = React.Children.toArray((element as WithChildren).props.children); +function isReactElementWithChildren(element: unknown): element is ReactElementWithChildren { + if (React.isValidElement(element)) { + if (element.props && element.props instanceof Object) { + return 'children' in element.props; + } + } - expect(kids).to.have.lengthOf(expectedParts.length); - kids.forEach((kid, index) => { - expect((kid as WithChildren).props.children).to.equal(expectedParts[index]); + return false; +} + +export function expectChildrenToMatch( + element: React.ReactElement<unknown>, + expectedParts: string[], +) { + if (!isReactElementWithChildren(element)) { + throw new Error('React element does not have children on it'); + } + + const elementChildren = React.Children.toArray(element.props.children); + expect(elementChildren).to.have.lengthOf(expectedParts.length); + elementChildren.forEach((elementChild, index) => { + if (!isReactElementWithChildren(elementChild)) { + throw new Error('React element child does not have children on it'); + } + + expect(elementChild.props.children).to.equal(expectedParts[index]); }); -}; +} |
