尝试使用react-testing-library
测试React.Suspense
时遇到一个奇怪的错误。该错误仅显示“不支持”,但未提供对该问题的任何真实了解。我遵循了Kent Dodds did on youtube的示例。
我发布了full code of my problem on github here,但这是测试代码的快照:
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"));
});
});
答案 0 :(得分:1)
我最近遇到了相同的错误。我注意到Kent的工作示例正在使用create-react-app
,并且想知道这是否是Babeling的Node / Jest特殊功能。由于使用了CRA,他的package.json
使用Babel预设react-app
。
尝试安装和配置插件babel-plugin-dynamic-import-node
(这是我认为我们需要的react-app
预设的特定部分)。我相信此插件会将动态导入转换为require
语句以供Node使用。更多信息: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>;