微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Bootstrap Dropdown未正确导入具有TypeScript的jestjs单元测试中

如何解决Bootstrap Dropdown未正确导入具有TypeScript的jestjs单元测试中

我是jest的新手,并为我们的以打字稿编写的react应用构建了这个简单的测试,该应用高度依赖react-bootstrap。我已经在酶和反应测试库中进行了尝试,并获得了相同的结果。我们也确实使用了webpack,但这似乎与这种情况无关。

somedropdown.test.tsx:

import * as React from "react";
import Dropdown from "react-bootstrap/Dropdown";
import DropdownButton from "react-bootstrap/DropdownButton";

import { render,screen } from "@testing-library/react";


interface SomeDropdownProps {
  onSelect(eventKey: string): void
}

function SomeDropdown(props: SomeDropdownProps): React.ReactElement<any,any> {
  return (
    <DropdownButton title="Some Dropdown" variant="outline-secondary">
      <Dropdown.Item eventKey="1" key="1" onSelect={props.onSelect}>1</Dropdown.Item>
      <Dropdown.Item eventKey="2" key="2" onSelect={props.onSelect}>2</Dropdown.Item>
    </DropdownButton>
  );
}

it("should work",() => {
  const onselect = (eventKey: string) => {};
  const { container } = render(<SomeDropdown onSelect={onselect} />);
  screen.debug(container);
});

这目前对我来说失败,并显示以下错误

    TypeError: Cannot read property 'Item' of undefined

      21 |   return (
      22 |     <DropdownButton title="Some Dropdown" variant="outline-secondary">
    > 23 |       <Dropdown.Item eventKey="1" key="1" onSelect={props.onSelect}>1</Dropdown.Item>
         |                 ^
      24 |       <Dropdown.Item eventKey="2" key="2" onSelect={props.onSelect}>2</Dropdown.Item>
      25 |     </DropdownButton>
      26 |   );

我的jest.config.js:

module.exports = {
  preset: 'ts-jest',testEnvironment: 'jsdom',testRegex: "(/src/ts/test/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",modulefileExtensions: ["ts","tsx","js","jsx","json"]
};

tsconfig.json

{
  "compilerOptions": {
    "module": "ES2020","moduleResolution": "node","target": "es6","rootDir": "./src/ts","outDir": "./build/js","sourceMap": true,"declaration": true,"removeComments": true,"noEmitOnError": true,"emitDecoratorMetadata": true,"experimentalDecorators": true,"allowSyntheticDefaultImports": true,"lib": [ "es7","dom" ],"noImplicitAny": true,"suppressImplicitAnyIndexErrors": true,"jsx": "react"
  },"include": [
    "./src/ts/**/*"
  ],"exclude": [
    "./src/ts/**/*.spec.ts"
  ]
}

解决方法

解决方案正在将"esModuleInterop": true添加到tsconfig.json。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。