reactjs - "Type Error : is not a function"在 Jest 测试中

标签 reactjs typescript jestjs enzyme

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 |   }
它在运行时正常工作。
有解决办法吗?

最佳答案

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

基于 TypeScript documentation on export = 正确的导入方式get-urls将使用 import = require()像这样的语法:

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

关于reactjs - "Type Error : is not a function"在 Jest 测试中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764495/

相关文章:

javascript - React-Router:如果未通过身份验证则显示主页,如果在 "/"中通过身份验证则显示仪表板

javascript - 如何正确键入将多个对象合并在一起的动态递归函数?

javascript - 如何 gitignore 快照文件夹?

javascript - 开 Jest 监视功能

reactjs - Babel意外的token编译react组件

reactjs - 使用 Nginx 在单个域上运行多个 React 应用程序

reactjs - 无法读取未定义、react-app-rewired 的属性 'use'

javascript - 遍历数组并将元素推送到对象

arrays - Angular 2 TS对象数组仅在订阅服务时定义

javascript - 使用 Jest 对 React 组件进行单元测试时如何模拟子组件