typescript 引用错误:使用React Router v6.4进行测试时,未定义请求

qf9go6mv  于 2022-12-14  发布在  TypeScript
关注(0)|答案(2)|浏览(217)

我正在尝试使用React测试库创建单元测试,通过单击React路由器链接来验证某些页面是否出现。我使用的设置与找到的答案here非常相似。当我运行测试时,得到的是ReferenceError: Request is not defined。由于我使用的是RouterProvider,因此无法完全按照React测试库文档进行操作。
我在专用文件中设置了路线:

export const routes: RouteObject[] = [{
    path: '/',
    element: <AppWrapper />,
    errorElement: <PageNotFoundScreen />,
    children: [{
        path: '/',
        element: <FeaturedSearchScreen />
    },{
        path: 'auth',
        element: <AuthScreen />,
        children: [{
            path: 'login',
            element: <LoginForm />
        },{
            path: 'signup',
            element: <SignUpForm />
        }]
        },{
            path: 'dashboard',
            element: <DashboardScreen />
        },{
            path: 'search',
            element: <SearchResultsScreen />,
            loader: searchLoader
        } 
    ]
}];

然后在测试文件中创建一个内存路由器

const router = createMemoryRouter(routes, {initialEntries: ['/']});
const user = userEvent.setup();
render(<RouterProvider router={router}/>);

我使用AppWrapper中的一个Outlet来呈现所有的子级。

预期

测试通过

结果

Vitest caught 1 unhandled error during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.

⎯⎯⎯⎯ Unhandled Rejection ⎯⎯⎯⎯⎯
ReferenceError: Request is not defined
 ❯ createRequest node_modules/@remix-run/router/router.ts:2654:3
 ❯ startNavigation node_modules/@remix-run/router/router.ts:886:19
 ❯ Object.navigate node_modules/@remix-run/router/router.ts:784:18
 ❯ push node_modules/react-router/lib/components.tsx:74:16
 ❯ navigate node_modules/react-router/lib/hooks.tsx:211:7
 ❯ internalOnClick node_modules/react-router-dom/index.tsx:727:9
 ❯ handleClick node_modules/react-router-dom/index.tsx:385:9
 ❯ HTMLUnknownElement.callCallback node_modules/react-dom/cjs/react-dom.development.js:4164:14
 ❯ HTMLUnknownElement.callTheUserObjectsOperation node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30
 ❯ innerInvokeEventListeners node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:350:25

当我渲染初始屏幕时,我能够验证所有组件,所以我知道我的设置基本上是工作的。它在等待新的页面标题时失败了。请随意查看此分支https://github.com/Thenlie/Streamability/tree/43-feat-test-suite上的整个代码

qacovj5a

qacovj5a1#

我最终需要创建一个定义Request的安装文件。

import { fetch, Request, Response } from "@remix-run/web-fetch";

if (!globalThis.fetch) {
  // Built-in lib.dom.d.ts expects `fetch(Request | string, ...)` but the web
  // fetch API allows a URL so @remix-run/web-fetch defines
  // `fetch(string | URL | Request, ...)`
  // @ts-expect-error
  globalThis.fetch = fetch;
  // Same as above, lib.dom.d.ts doesn't allow a URL to the Request constructor
  // @ts-expect-error
  globalThis.Request = Request;
  // web-std/fetch Response does not currently implement Response.error()
  // @ts-expect-error
  globalThis.Response = Response;
}

然后可以在测试配置文件中引用它,对我来说是vitest.config.ts

import { defineConfig } from 'vitest/config';

// https://vitest.dev/guide/#configuring-vitest
export default defineConfig({
    test: {
        environment: 'jsdom',
        setupFiles: './src/__tests__/setup.ts',
        globals: true,
        watch: false
    }
});
jw5wzhpr

jw5wzhpr2#

我用“jest-fetch-mock”(https://www.npmjs.com/package/jest-fetch-mock)解决了这个问题
对于TypeScript/ES6,将以下行添加到setupTests.ts文件中测试用例的开头(在任何其他导入之前)。

import { enableFetchMocks } from 'jest-fetch-mock'
enableFetchMocks();

相关问题