catalog: EntitySwitch render children when entity is not found

Signed-off-by: Vincenzo Scamporlino <vincenzos@spotify.com>
This commit is contained in:
Vincenzo Scamporlino
2023-08-17 15:37:08 +02:00
parent 3b5eb94a4f
commit 35bba616b7
2 changed files with 56 additions and 5 deletions
@@ -59,6 +59,50 @@ describe('EntitySwitch', () => {
expect(screen.queryByText('C')).not.toBeInTheDocument();
});
it('should render the default case if entity is not found', () => {
const content = (
<EntitySwitch>
<EntitySwitch.Case if={isKind('component')} children="A" />
<EntitySwitch.Case if={isKind('api')} children="B" />
<EntitySwitch.Case children="C" />
</EntitySwitch>
);
render(
<Wrapper>
<AsyncEntityProvider entity={undefined} loading={false}>
{content}
</AsyncEntityProvider>
</Wrapper>,
);
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
expect(screen.queryByText('C')).toBeInTheDocument();
});
it(`shouldn't render any children if entity is loading and no entity exists in the context`, () => {
const content = (
<EntitySwitch>
<EntitySwitch.Case if={isKind('component')} children="A" />
<EntitySwitch.Case if={isKind('api')} children="B" />
<EntitySwitch.Case children="C" />
</EntitySwitch>
);
render(
<Wrapper>
<AsyncEntityProvider entity={undefined} loading>
{content}
</AsyncEntityProvider>
</Wrapper>,
);
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
expect(screen.queryByText('C')).not.toBeInTheDocument();
});
it('should render the fallback if no cases are matching', () => {
const content = (
<EntitySwitch>
@@ -170,7 +214,7 @@ describe('EntitySwitch', () => {
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
expect(screen.queryByText('C')).not.toBeInTheDocument();
expect(screen.queryByText('C')).toBeInTheDocument();
});
it('should switch child when filters switch', () => {
@@ -64,7 +64,7 @@ export interface EntitySwitchProps {
/** @public */
export const EntitySwitch = (props: EntitySwitchProps) => {
const { entity } = useAsyncEntity();
const { entity, loading } = useAsyncEntity();
const apis = useApiHolder();
const results = useElementFilter(
@@ -77,14 +77,21 @@ export const EntitySwitch = (props: EntitySwitchProps) => {
})
.getElements()
.flatMap<SwitchCaseResult>((element: ReactElement) => {
// If the entity is missing or there is an error, render nothing
if (!entity) {
if (loading && !entity) {
return [];
}
const { if: condition, children: elementsChildren } =
element.props as EntitySwitchCase;
if (!entity) {
return [
{
if: condition === undefined,
children: elementsChildren,
},
];
}
return [
{
if: condition?.(entity, { apis }),
@@ -92,7 +99,7 @@ export const EntitySwitch = (props: EntitySwitchProps) => {
},
];
}),
[apis, entity],
[apis, entity, loading],
);
const hasAsyncCases = results.some(