Search code examples
typescriptreact-nativetypescript-typingsdefinitelytypedtype-declaration

How to write the tests for a React Native library for DefinitelyTyped?


I wanted to contribute to the rn-placeholder library for React Native by providing the types for DefinitelyTyped. This is my first time contributing an index.d.ts file to DefinitelyTyped.

I wrote the declaration file. Now I want to write the mandatory rn-placeholder-tests.ts file. But when I try to use my declarations I get regexp errors:

[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'.

I even tried just duplicating tests from @types/react-native and they give the same errors:

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

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

Here is my 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"]
}

The other files are just how they are generated when using npx dts-gen --dt --name my-package-name --template module.

How can I get the tests to pass?

EDIT: I converted the rn-placeholder-tests.ts to .tsx which gets rid of the regexp error. But now TSLint complains that it can't find the modules:

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

What is going on?


Solution

  • Changing the .ts to .tsx is the right move as far as the file extension. (See more info here about tsx: https://www.typescriptlang.org/docs/handbook/jsx.html)

    For the other "Cannot find module" errors, see this "typescript: Cannot find module 'react'" issue.

    It could be that you need to add the type definitions:

    npm i -D @types/react
    

    Or, perhaps you simply need to add "moduleResolution" to your tsconfig.json file:

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