21 Mar 2023
12:29 AM
- last edited on
20 Apr 2023
12:35 AM
by
educampver
Hi all,
I'm currently using the ExpandableSection in my app and I want to test with Jest the following behavior:
I'm simulating an fireEvent.click() an check afterwards if the components are defined/throwing. Unfortunately, I'm failing to write the proper test for case 2.
import { ExpandableSection } from '@dynatrace/strato-components-labs';
export const MyComponent = () => {
const [isClosed, setIsClosed] = useState<boolean>(false);
const onChangeExpandable = () => {
setIsClosed((prev) => !prev);
};
return (
<>
<ExpandableSection
variant={'heading-3'}
defaultOpen={true}
label={'Global'}
onOpenChange={() => onChangeExpandable()}
data-testid='expandable'
>
<AComponent data-testid='a-component'/>
</ExpandableSection>
{/* Show component if expandable section is closed */}
{isClosed ? <BComponent data-testid='b-component' /> : null}
</>
);
};
My test for case 2 looks as follows
it('Should show BComponent and should not show AComponent if expandable is closed', async () => {
// given
render(<MyComponent />);
// when
const expandable = await screen.findByTestId('expandable');
fireEvent.click(expandable.querySelector('button') as Element);
const bComponent = await screen.findByTestId('b-component');
// then
await expect(screen.findByTestId('a-component')).rejects.toThrow();
expect(bComponent).toBeDefined();
});
The test is failing because the promise is resolved, and not rejected. But why?
Some further general questions:
Solved! Go to Solution.
Hi,
did you check if component A is still rendered even if they the section isn't expanded? If so, maybe
expect(screen.findByTestId('a-component')).not.toBeVisible();
would be the better choice.
Since it is a component from the design system I would expect that you don't have to test it's functionality since it's already tested internally.
Thanks for your answer! The expect(...).not.toBeVisible() is the better choice!
Hi Melanie, it may be because the ExpandableSection only removes the component once the animation is finished. Using waitFor should work:
import { waitFor } from "@dynatrace/strato-components-preview/testing";
await waitFor(async () => {
expect(await screen.findByTestId('a-component')).not.toBeVisible();
});
You can read more about the waitFor options here.
Thank you! That did the trick