storybook [Bug]: 在便携式故事中使用beforeAll时,类型可能未定义,

o2rvlv0m  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(36)

描述bug

在setupTests.ts文件中应用以下示例代码以设置vitest项目的注解:

import { beforeAll } from "vitest";
import { setProjectAnnotations } from "@storybook/react";
import { render as testingLibraryRender } from "@testing-library/react";
import * as storybookAnnotations from "./.storybook/preview";

const annotations = setProjectAnnotations([
  storybookAnnotations,
  { testingLibraryRender },
]);

// ERROR
beforeAll(annotations.beforeAll);

annotations.beforeAll 可能未定义,尽管它始终是一个函数,即使用户没有定义 beforeAll
我们应该修复 setProjectAnnotations 返回的类型,使其始终将 beforeAll 设置为所需。

polhcujo

polhcujo1#

为了解决 annotations.beforeAll 可能未定义的问题,请更新 setProjectAnnotations 函数中的类型定义,以确保 beforeAll 始终被定义。

  • 更新类型定义:
  • /code/renderers/react/src/portable-stories.tsx/code/renderers/vue3/src/portable-stories.ts 中修改 setProjectAnnotations 的返回类型,以确保 beforeAll 始终被定义。
export function setProjectAnnotations(
  projectAnnotations: NamedOrDefaultProjectAnnotations<ReactRenderer> | NamedOrDefaultProjectAnnotations<ReactRenderer>[]
): ProjectAnnotations<ReactRenderer> & { beforeAll: NonNullable<ProjectAnnotations<ReactRenderer>['beforeAll']> } {
  return originalSetProjectAnnotations<ReactRenderer>(projectAnnotations) as ProjectAnnotations<ReactRenderer> & { beforeAll: NonNullable<ProjectAnnotations<ReactRenderer>['beforeAll']> };
}
  • 更新测试:
  • 确保 /code/core/src/preview-api/modules/store/csf/portable-stories.test.ts 中的测试反映了新的类型定义。
it('should return composed beforeAll as part of project annotations', async () => {
  const after = vi.fn();
  const before = vi.fn((n) => () => after(n));
  const finalAnnotations = setProjectAnnotations([
    { beforeAll: () => before(1) },
    { beforeAll: () => before(2) },
    { beforeAll: () => before(3) },
  ]);

  const cleanup = await finalAnnotations.beforeAll?.();
  expect(before.mock.calls).toEqual([[1], [2], [3]]);

  await cleanup?.();
  expect(after.mock.calls).toEqual([[3], [2], [1]]);
});

参考资料

/code/renderers/react/src/portable-stories.tsx
/code/renderers/vue3/src/portable-stories.ts
/code/core/src/preview-api/modules/store/csf/portable-stories.test.ts
/code/core/src/preview-api/modules/store/csf
/code/core/src/preview-api/modules/store/StoryStore.test.ts

关于 Greptile

此响应为您提供了研究的起点,而非精确的解决方案。
帮助我们改进!如果这有帮助,请留下一个 👍,如果不相关,请留下一个 👎。

相关问题