2

尝试使用react-testing-libraryto test时遇到一个奇怪的错误React.Suspense。该错误只是说“不支持”,但没有对问题提供任何真正的洞察力。我遵循了Kent Dodds 在 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"));
  });
});
4

1 回答 1

2

我最近遇到了同样的错误。我注意到 Kent 的工作示例正在使用create-react-app,并且想知道它是否在为 Node/Jest 做一些特殊的 Babeling。由于使用了 CRA,他package.json使用了 babel 预设react-app

尝试安装和配置插件(这是我认为我们需要的预设babel-plugin-dynamic-import-node的特定部分)。react-app我相信这个插件将动态导入转换require为 Node.js 的语句。更多信息: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"
]

...这应该足以克服Not Supported错误。

顺便说一句,我注意到您的一个名为“它延迟加载本地组件”的测试随后因以下错误而失败:

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>;
于 2019-06-06T01:07:56.240 回答