如何为DefiniteTyped 编写React Native 库的测试?

Posted

技术标签:

【中文标题】如何为DefiniteTyped 编写React Native 库的测试?【英文标题】:How to write the tests for a React Native library for DefinitelyTyped? 【发布时间】:2019-04-21 20:14:02 【问题描述】:

我想通过提供 DefinitelyTyped 的类型来为 React Native 的 rn-placeholder 库做出贡献。这是我第一次将index.d.ts 文件贡献给DefiniteTyped。

我编写了声明文件。现在我想编写强制性的rn-placeholder-tests.ts 文件。但是当我尝试使用我的声明时,我得到regexp 错误:

[ts]
Conversion of type 'RegExp' to type 'View' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Property 'measure' is missing in type 'RegExp'.

我什至尝试从 @types/react-native 复制测试,但它们给出了相同的错误:

import * as React from 'react';
import  Text, View  from "react-native";

class CustomView extends React.Component 
  render() 
    return <View />
  

这是我的tsconfig.json


    "compilerOptions": 
        "module": "commonjs",
        "lib": ["es6"],
        "noImplicitAny": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        "jsx": "react",
        "baseUrl": "../",
        "typeRoots": ["../"],
        "types": [],
        "noEmit": true,
        "forceConsistentCasingInFileNames": true
    ,
    "files": ["index.d.ts", "rn-placeholder-tests.ts"]

其他文件就是使用npx dts-gen --dt --name my-package-name --template module时的生成方式。

我怎样才能让测试通过?

编辑:我将rn-placeholder-tests.ts 转换为.tsx,从而消除了regexp 错误。但是现在 TSLint 抱怨它找不到模块:

[ts] Cannot find module 'react'.
[ts] Cannot find module 'react-native'.
[ts] Cannot find module 'rn-placeholder'.

发生了什么事?

【问题讨论】:

【参考方案1】:

就文件扩展名而言,将 .ts 更改为 .tsx 是正确的做法。 (在此处查看有关 tsx 的更多信息:https://www.typescriptlang.org/docs/handbook/jsx.html

有关其他“找不到模块”错误,请参阅此"typescript: Cannot find module 'react'" issue。

可能是你需要添加类型定义:

npm i -D @types/react

或者,也许您只需将“moduleResolution”添加到您的 tsconfig.json 文件中:

"compilerOptions": 
          ...
          "moduleResolution": "node" <---------- this entry
          ...

【讨论】:

以上是关于如何为DefiniteTyped 编写React Native 库的测试?的主要内容,如果未能解决你的问题,请参考以下文章