reactjs 对函数调用shouldHaveBeenCalled时,storybook + jest播放方法失败

mwyxok5s  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(77)

我有这个组件:

import {
  FC,
  ReactElement,
  useState,
  MouseEvent as ReactMouseEvent,
  ChangeEvent as ReactChangeEvent,
} from 'react';

import { Stack, TablePagination } from '@mui/material';

export const Pagination: FC<IPaginationProps> = ({
  total,
  page = 1,
  rowsPerPage = 25,
  position = 'start',
  rowsPerPageOptions = [10, 25, 50, 100],
  onPageChange,
  onRowsPerPageChange,
}): ReactElement => {
  const [localPage, setPage] = useState(page);
  const [localRowsPerPage, setRowsPerPage] = useState(rowsPerPage);

  const handleChangePage = (event: ReactMouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setPage(newPage);
    onPageChange({ page: newPage, total, rowsPerPage: localRowsPerPage });
  };

  const handleChangeRowsPerPage = (
    event: ReactChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const perPage = parseInt(event.target.value, 10);
    setRowsPerPage(perPage);
    setPage(0);
    onRowsPerPageChange({ page: 0, total, rowsPerPage: perPage });
  };

  return (
    <Stack direction="row" justifyContent={`flex-${position}`}>
      <TablePagination
        component="div"
        showFirstButton
        showLastButton
        count={total}
        page={localPage}
        onPageChange={handleChangePage}
        rowsPerPage={localRowsPerPage}
        onRowsPerPageChange={handleChangeRowsPerPage}
        rowsPerPageOptions={rowsPerPageOptions}
      />
    </Stack>
  );
};

我为它写了一个故事:

export default {
  title: 'Components/Pagination',
  component: Pagination,
  parameters: {
    actions: {
      handles: ['click'],
    },
  },
  args: {
    total: 100,
    page: 1,
    onPageChange: ({ page }) => {
      // eslint-disable-next-line no-console
      console.log({ page });
    },
    onRowsPerPageChange: ({ rowsPerPage }) => {
      // eslint-disable-next-line no-console
      console.log({ rowsPerPage });
    },
  },
  decorators: [
    (Story) => (
      <div style={{ margin: '3em', boxShadow: '7px 5px 14px -8px rgba(0,0,0,0.55)' }}>
        {Story()}
      </div>
    ),
  ],
} as ComponentMeta<typeof Pagination>;

const Template: ComponentStory<typeof Pagination> = ({ ...args }) => <Pagination {...args} />;

export const Default = Template.bind({});
Default.play = async ({ canvasElement, args }) => {
  const onPageChangeSpy = jest.spyOn(args, 'onPageChange');
  const canvas = await within(canvasElement);

  const prevBtn = canvas.getByLabelText('Go to previous page');
  await userEvent.click(prevBtn);
  await expect(onPageChangeSpy).toHaveBeenCalled();
};

我可以看到按钮被单击,并且onPageChange被调用,因为分页相应地改变,但是测试失败:
预期呼叫数:〉= 1
已接来电数:0
最奇怪的是,如果我在StoryBook的交互选项卡中点击重新运行,一切都正常了。

wlzqhblo

wlzqhblo1#

称之为愚蠢,但我意识到,只是改变**toHaveBeenCalled();toHaveBeenCalled;**工作。

相关问题