测试suspense时出现“不支持的错误”

3
我在使用react-testing-library测试React.Suspense时遇到了一个奇怪的错误。这个错误只是说“不支持”,但没有给出任何关于问题的实质性见解。我按照肯特·道德在Youtube上的示例进行操作。
我在github上发布了我问题的完整代码,但这里是测试代码的快照:
import React from "react";

import { render, waitForElement, cleanup } from "react-testing-library";
import MyOtherPackageThing from "my-package/lib/my-thing";
import LazyThing from "../src/index";

afterEach(cleanup);

test("it works", async () => {
  const { getByText, debug } = render(<MyOtherPackageThing />);

  await waitForElement(() => getByText("my thing"));

  expect(getByText("my thing"));
});

describe("these fail with 'Not Supported'", () => {
  test("it lazy loads a local component", async () => {
    const LazyLocalThing = React.lazy(() => import("../src/LocalThing"));
    const { getByText, debug } = render(
      <React.Suspense fallback="Loading...">
        <LazyLocalThing />
      </React.Suspense>
    );
    debug();
    await waitForElement(() => getByText("my local thing"));
    debug();
    expect(getByText("my local thing"));
  });

  test("it says not supported, like wtf", async () => {
    const { getByText, debug } = render(<LazyThing />);
    debug();
    await waitForElement(() => getByText("my thing"));
    debug();
    expect(getByText("my thing"));
  });
});

你能分享更多关于这个问题的细节吗?当我在my-consumer-pkg中尝试运行yarn jest时,出现了一些错误,我可以看到一些很长的日志。也许你应该在那个测试包中开一个issue,因为在这里找到帮助会很困难,这是一个高度专业化的问题。 - zishe
@zishe 当然,您想了解什么?Github上的代码有一个自述文件,说明如何进行复制。我把所有东西都放在了run.sh中,所以您设置它时不应该遇到任何问题。 - Ben
我创建了一个问题 https://github.com/benmonro/not-supported-rtl-suspense/issues/1 ,但是我没有看到任何 run.sh 文件。 - zishe
1个回答

2
我最近也遇到了同样的错误。我注意到Kent的工作示例使用了create-react-app,想知道它是否为Node/Jest特别设置了Babel。因此,他的package.json使用了babel预设react-app
尝试安装和配置插件babel-plugin-dynamic-import-node(我认为我们需要react-app预设的特定部分)。我相信这个插件会将动态导入转换为Node的require语句。更多信息:https://www.npmjs.com/package/babel-plugin-dynamic-import-node 安装插件:
npm i --save-dev babel-plugin-dynamic-import-node

在我的消费者包/my-consumer-pkg/babel.config.js中添加插件:
请添加以下插件:
plugins: [
    ...
    "babel-plugin-dynamic-import-node"
]

...这应该足以解决“不支持”的错误。

另外,我注意到你的一个测试命名为“它懒加载本地组件”,随后出现了以下错误:

Original Answer:

Not Supported

Translated Answer:

不支持

Element type is invalid. Received a promise that resolves to: [object Object]. Lazy element type must resolve to a class or function.

因此,我进行了小改动,使 LocalThing 成为一个函数。

最初的回答

const LocalThing = () => <div>my local thing</div>;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接