【问题标题】:"Type Error : is not a function" in a Jest testJest 测试中的“类型错误:不是函数”
【发布时间】:2020-01-05 22:28:52
【问题描述】:

经过 Jest 和 Enzyme 测试的组件具有一些功能。然后这个函数使用一个导入的库。

它犯了一些错误。

测试代码

it('Emoji should be rendered without error', () => {
    const messageItem = shallow(
      <MessageItem {...props}/>
    )
   ...
})

消息项

import * as getUrls from 'get-urls';

export class MessageItem extends Component <Props> {
  state = {
    isOpenThread: false,
    isAddEmoji: false,
    containedUrl: ''
  }

  getContainUrl = () => {
    //getUrls makes an error!
    const urls = getUrls(this.props.content).values();
    const firstUrl: string = urls.next().value;
    return firstUrl
  }
  ...
  render(){
    return (... <UrlInfoArea {...props} url={this.getContainUrl()} />))
  }
}

错误信息

 TypeError: getUrls is not a function

      37 |
      38 |   getContainUrl = () => {
    > 39 |     const urls = getUrls(this.props.content).values();
         |                  ^
      40 |     const firstUrl: string = urls.next().value;
      41 |     return firstUrl
      42 |   }

它在运行时正常工作。

有解决办法吗?

【问题讨论】:

  • 你能分享你的tsconfig.json吗?尝试在tsconfig.json 中将"esModuleInterop": true 添加到您的compilerOptions
  • 我试过了。但它是相同的状态。 {“compilerOptions”:{“target”:“es5”,“baseUrl”:“./”,“rootDir”:“./”,“jsx”:“react”,“module”:“es2015”,“moduleResolution “:“节点”,“noUnusedLocals”:真,“漂亮”:真,“sourceMap”:真,“resolveJsonModule”:真,“esModuleInterop”:真,“lib”:[“es2015”,“dom”]} , "排除": ["node_modules", "*/node_modules/"] }

标签: reactjs typescript jestjs enzyme


【解决方案1】:

get-urls 导出单个函数和get-urls uses the export = syntax 的类型定义。

基于TypeScript documentation on export =,导入get-urls 的正确方法是使用import = require() 语法,如下所示:

import getUrls = require('get-urls');

【讨论】:

  • 这是 typescript 这样的 ECMAScript 模块中的 make 错误。考虑使用 'import * as ns from "mod"'、'import {a} from "mod"'、'import d from "mod"' 或其他模块格式。ts(1202)'
猜你喜欢
  • 2019-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-03
  • 2020-10-22
  • 2020-07-31
  • 2020-02-28
  • 2019-07-31
相关资源
最近更新 更多