Unit testing react2angular components with Karma Jasmine and Enzyme

I have been using react2angular library for plugging ReactJS components into my AngularJS Application so that I could start writing ReactJS today without having to migrate over the entire application. The real power of react2angular is where it offers you the ability to $inject your angular services/filters/factories right into your react components so it can use them directly. In doing so, I have a bunch of AngularJS services that I want to be available in my React components. To accomplish this I've been passing $injector into the components with react2angular like so:

Then in the ReactJS components I grab $injector off the props and use it to get access to all of my AngularJS services, factories, etc. For example if I wanted to get the $stateParams for the current URL I can do $injector.get('$stateParams');.

Downstream Components

Obviously for downstream components I don't keep reusing react2angular so how do I get access to the $injector or other angular services? Well for now I pass those down to the children via props. You can see that on line 25 above.

But how do I unit test that?

This was all well and good until I went to write a unit test for the Component and realized, since I wasn't starting from my parent react2angular component I didn't have a reference to $injector to pass to the component. So here's how I did that.

You can see I include react, angular, and shallow. Shallow is used for shallow-loading a react component into the DOM as well as gives us a bunch of jQuery-like methods for querying and interacting w/ the DOM. On Line 7 I include the React component I'm trying to test. The rest should all look pretty familiar if you've ever written Jasmine tests for AngularJS components.

If you want to learn more about ng-mock, angular.mock.module and angular.mock.inject I recommend reading this article.

Setup behind the scenes

So obviously I had to do a little work to get this working.

Install some new dependencies

npm install the following:

    "jasmine-enzyme": "^6.0.4",
    "enzyme": "^3.6.0",
    "enzyme-adapter-react-16": "^1.5.0",

Create an enzyme.js file

You have to create an enzyme.js file for configuring your enzyme adaptor.

Include the Enzyme.js file

I included the enzyme.jz file in my tests.webpack.js since I was following the alternate Karma setup.

// This file is an entry point for angular tests
// Avoids some weird issues when using webpack + angular.

require('angular');
require('angular-mocks/angular-mocks');
import './enzyme.js';

var context = require.context('./src', true, /_test\.js$/);
context.keys().forEach(context);

Include shallow from enzyme

   import {shallow} from 'enzyme';
   ... Do unit test stuff ...