Adding Jest To Sharepoint Framework React Sites in 2020
I recently started a project where I had to work on a yeoman generated sharepoint framework react site. This is the Microsoft recommended way to create a webpart for Sharepoint Online build with React.
To be 100% clear, this is how the yeoman generator was installed.
And, this is how the generated framework was set up.
SPFX, React, TypeScript, and adding Jest + Enzyme
This SPFX generator creates a hello world set up with React, TypeScript, Gulp, and Mocha. I wanted to use Jest and Enzyme - here is my tale of how I tried to set this up and got about 90% there.
First, install some more things:
Wire up jest in tsconfig.json
Note: I’m just showing here what changed
Make a setupTests.ts file
In this setupTests.ts
file, we are going to set up the enzyme adapter
Configure Jest options in package.json
These go in package.json
, again just showing what changed.
If you want to add code coverage, here are some additional options
These also go in package.json
Make sure to .gitignore
the jest directory if you add this coverage config (jest/
).
Now you can create tests!
Here is an example test file (src/components/example.test.tsx
). Note that I imported react and named it .tsx
when I’m using enzyme.
But wait, there is an issue with microsoft fabric!
I tried testing a React file where I imported the Text
component from office-ui-fabric-react
and ran up against this issue.
It seems like these files are not being transformed and jest needs them transformed to run them.
For the record these are the various versions of things I’m using:
Finally found the issue
I googled something like “office-ui-fabric-react jest failing export * from” and I was eventually let to this note in the documentation for fabric that notes they have multiple outputs you can switch between.
Sure enough for jest you need to use the commonJs
variant, and fixing everything was as simple adding this to my jest config:
Final note
There is a pretty good sample repo here: https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/react-jest-testing
If you want to use that to get started (and then also use Fabric) you just need to make sure to add the module mapper I listed above. That should cover it (at least in January 2020).