Search code examples
angularjestjsstorybookangular-storybook

Storybook and Angular interactions play test 'expect is not defined'


I have been trying to get Storybook interaction tests working for our production Angular application. We have existing tests using Karma/Jasmine but we'd like to implement Storybook testing for more UI driven tests.

Stories are defined in .stories.ts files next to the component files as such:

import { Meta, Story } from '@storybook/angular';
import { userEvent, within } from '@storybook/testing-library';
import { CounterComponent } from "./counter.component";

export default {
  component: CounterComponent,
  title: 'Components/Counter',
  excludeStories: /.*Data$/,
} as Meta;

const Template: Story = () => ({});

export const Default = Template.bind({});
Default.play = async ({ canvasElement }) => {
  const canvas = within(canvasElement);

  await expect(canvas.getByTestId('text').innerHTML).toBe('0');

  await userEvent.click(canvas.getByRole('button'));

  await expect(canvas.getByTestId('text').innerHTML).toBe('1');
};

But when building or running Storybook tests I run into the error cannot find name 'expect' or expect is not defined.
I have tried explicitly importing expect from @jest/globals but this is not possible.
I have tried looking into assigning various things to global in preview.ts/js but failed to fix my errors.

I've recreated it in this repository https://github.com/bertcardinaels/storybook-angular-test

Any help or pointers are appreciated as this should be possible right?


Solution

  • For me, adding

    import { expect } from '@storybook/jest';
    

    helped. As long as storybook is already running, everything is fine. But when I restart storybook, I get unfortunately an error:

    error TS4111: Property 'toBeFalse' comes from an index signature, so it must be accessed with ['toBeFalse'].

    in some other, non storybook related tests now. Probably because the type definitions of karma/jasmine are colliding with jest.

    If somebody knows how to fix that ... :)