Create-react-app: Type check test files

Created on 30 Oct 2018  路  8Comments  路  Source: facebook/create-react-app

Bug report

I created a new project with the --typescript flag, and added a type for my component's props like so:

type AppProps = {
  name: string
};

class App extends Component<AppProps> {
  render() {
    return (
      ...
    );
  }
}

In index.tsx when I write something like (note the missing prop):

ReactDOM.render(<App />, document.getElementById('root')); // name prop is missing

I get an error in both my editor (VSCode) and on my console when I run yarn start.

However in my tests if I have something like:

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

I get the type error in my editor but NOT when I run yarn test, the tests run successfully in fact.

Is this intended?

typescript breaking change enhancement

Most helpful comment

This is also happening to me. Any updates?

All 8 comments

Check out your tsconfig.json.

Change this to an empty array if you want to include them

  "exclude": [
    "**/__tests__/**",
    "**/?*test.*",
    "**/?*spec.*"
  ]

the types are checked in the build script

This is currently a known limitation. We can check these types in the future.

For now, please rely on VSCode to type check your tests or run tsc.

Another option, update your test scripts to run tsc.

Update your package.json file:

- "test": "react-scripts test",
+ "test": "tsc && react-scripts test",

The tsc command will look for compiler options in the tsconfig.json file if one exists.

Additional Optional Solutions

If you have a different testing script for CI then add tsc to that one too:

"test:ci": "CI=true tsc && react-scripts test --env=jsdom --coverage",

If you're using husky, add tsc to your pre-commit hook:

  "husky": {
    "hooks": {
      "pre-commit": "tsc && lint-staged"
    }
  },

We can also use ts-jest which does the actual typechecking in jest.

We can also use ts-jest which does the actual typechecking in jest.

The future of ts-jest is uncertain. We are eager to get some form of type checking in for test files, but we also don't want to adopt a library that potentially won't be maintained going forward. We are exploring other options to satisfy this that better fits in our current ecosystem of tools.

This is also happening to me. Any updates?

FYI: https://github.com/kulshekhar/ts-jest/pull/1549 will be in alpha version of ts-jest (possibly today). You can test the alpha version and give some feedbacks for https://github.com/kulshekhar/ts-jest/issues/1115

Was this page helpful?
0 / 5 - 0 ratings