javascriptreactjsstorybook

Storybook interaction tests that update the dom


I have a react component that opens a popover on the click of a button. I am testing the interaction using storybook.

await step('Click right button to tomorrow', async () => {
      fireEvent.click(canvas.getByTestId('right-arrow'));
      expect(canvas.getByTestId('daily-button-tomorrow')).toBeInTheDocument();
    });

The element with test id only appears in the DOM after the button is clicked. In the image you can see the data-testid is in the DOM but story book fails.

enter image description here

Am I going about testing UI with storybook in the wrong manner or am I missing something?


Solution

  • You probably need to await the click event since this is also an async operation.

    await step('Click right button to tomorrow', async () => {
          await fireEvent.click(canvas.getByTestId('right-arrow'));
          expect(canvas.getByTestId('daily-button-tomorrow')).toBeInTheDocument();
    });
    

    If that doesn't work you could consider adding a timeout between the action and the assert. I would recommend to not use this approach if it can be avoided.

    await new Promise((resolve) => setTimeout(resolve, 100));