gpt4 book ai didi

reactjs - 测试悬念时不支持错误

转载 作者:行者123 更新时间:2023-11-28 20:10:25 24 4
gpt4 key购买 nike

我在尝试使用 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"));
});
});

最佳答案

我最近遇到了同样的错误。我注意到 Kent 的工作示例使用的是 create-react-app 并且想知道它是否是 Babeling 对 Node/Jest 有什么特别的东西。由于使用了 CRA,他的 package.json 使用了 babel preset react-app

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

...这应该足以解决 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>;

关于reactjs - 测试悬念时不支持错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55094484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com