Pass router context to child components when testing in Enzyme/Jest

Adding a Link to a React component was easy as it sounds, except that it broke half of the unit tests. I started getting “Invariant Violation: You should not use <Link> outside a <Router>” which explains itself, but sorting it out took quite some time. In my component I’ve been using withRouter, but the tests are done on a disconnected component without the router and the Link component requires the router context. While mostly understood the issue, when trying most of the suggestions, I kept getting the above error, or “Warning: Failed context type: The context router is marked as required in Component, but its value is undefined“. So let’s see how to pass the router context to child components when testing in Enzyme/Jest.



Tagged with
Comment

React on TypeScript – Part 2

In the previous post I left some React on TypeScript build flow steps to my future self. The project is already in a pretty decent shape, TypeScript is working, there is linting, CSS modules support and unit testing. Now just adding some more loaders to Webpack to handle images and other files and Babel to add some more browser compatibility. I will continue working on the repository which I created in the previous post, check it out if you want to see how we got here.



Tagged with
Comment

Build and test React with TypeScript

For my test projects I’ve been using create-react-app, which is very nice to kick start a React project in Webpack build flow. Unfortunately making it work with TypeScript is somewhat a pain (doable though) as for example new versions of TS loaders will not work with Webpack 3 anymore which is used by the current version of create-react-app. Instead of using old libraries, let’s see what it takes to bootstrap a React web project/build workflow including:

  • build workflow setup using Webpack 4
  • TypeScript support
  • TS linting for code style checking
  • CSS module support to avoid clashing with other components
  • support unit testing with Jest and Enzyme

These are mostly fairly well documented things, you will find more details for each tools on their respective website. Here I summarize the steps and create a working configuration. At the end of the blog post you will also find a link to the complete repository.



Tagged with
Comment