SPFx - Unit Test With Jest And Enzyme

In this article, we will develop unit tests for SPFx solutions using Enzyme and Jest JavaScript Testing Framework.

Introduction

 
Testing is an important phase of the software life cycle. It should be a part of continuous development and deployment to achieve better results. SharePoint Framework is no exception to this. As a part of SPFx solution development, we should have supporting test cases to test the functionality independently or as regression testing. Having significant test cases help to develop new functionalities by ensuring the integrity of the existing functionality.
 

Importance of unit testing

 
Unit testing is important because of the following reasons
  • Early bug detection
  • Makes the process agile
  • Improves the quality of code
  • Facilitates changes and simplifies integration
  • Provides documentation of the system
  • Simplifies debugging process

Create SPFx Web Part

 
Open a command prompt. Create a directory for SPFx solution.
  1. md spfx-jest-test  
Navigate to the above-created directory.
  1. cd spfx-jest-test  
Run the Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Yeoman generator will present you with the wizard by asking questions about the solution to be created.
 
SPFx - Unit Test With Jest And Enzyme
 
Solution Name: Hit Enter to have default name (spfx-jest-test in this case) or type in any other name for your solution.
Selected Choice: Hit Enter
 
Target for the component: Here we can select the target environment where we are planning to deploy the client web part i.e. SharePoint Online or SharePoint On-Premises (SharePoint 2016 onwards).
Selected Choice: SharePoint Online only (latest)
 
Place of files: We may choose to use the same folder or create a sub-folder for our solution.
Selected Choice: Same folder
 
Deployment option: Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
Selected Choice: N (install on each site explicitly)
 
Permissions to access web APIs: Choose if the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant.
Selected choice: N (solution contains unique permissions)
 
Type of client-side component to create: We can choose to create a client-side web part or an extension. Choose web part option.
Selected Choice: WebPart
 
Web part name: Hit enter to select the default name or type in any other name.
Selected Choice: SPFxTest
 
Web part description: Hit enter to select the default description or type in any other value.
Selected Choice: Unit test SPFx with Jest
 
Framework to use: Select any JavaScript framework to develop the component. Available choices are (No JavaScript Framework, React, and Knockout)
Selected Choice: React
 
Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command.
  1. npm shrinkwrap  
In the command prompt type the below command to open the solution in the code editor of your choice.
  1. code .  
Update render method of the React component “src\webparts\spFxTest\components\SpFxTest.tsx” to execute the test cases against.
  1. public render(): React.ReactElement<ISpFxTestProps> {  
  2.   return (  
  3.     <div className={ styles.spFxTest } id="spfxTest">  
  4.       <div className={ styles.container }>  
  5.         <div className={ styles.row }>  
  6.           <div className={ styles.column }>  
  7.             <span className={ styles.title }>Welcome to SharePoint!</span>  
  8.             <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>  
  9.             <h1 className={styles.title}>SPFx Test webpart</h1>  
  10.             <p className={ styles.description }>{escape(this.props.description)}</p>  
  11.             <a href="https://aka.ms/spfx" className={ styles.button }>  
  12.               <span className={ styles.label }>Learn more</span>  
  13.             </a>  
  14.           </div>  
  15.         </div>  
  16.       </div>  
  17.     </div>  
  18.   );  
  19. }  

NPM Packages Used

 
Enzyme
 
Developed by Airbnb, it represents test utilities for React. On the command prompt, run the below command.
  1. npm install enzyme enzyme-adapter-react-16 react-test-renderer @types/enzyme --save-dev --save-exact   
Jest
 
It supports asserts, mocking, code coverage, coverage threshold for continuous deployment, and summary report.
  1. npm install jest jest-junit ts-jest @types/jest --save-dev --save-exact  
identity-obj-proxy
 
Allows to test SASS / LESS / CSS imports.
  1. npm install identity-obj-proxy --save-dev --save-exact  

Setup Jest with SPFx

 
We will use Jest to install npm packages in our SPFx solution.
 
Open the package.json file.
 
Under the “Scripts” section for “test” configuration, replace “gulp test” with “jest”.
 
SPFx - Unit Test With Jest And Enzyme
 
Add “jest” configuration after “devDependencies”.
  1. "jest": {  
  2.   "moduleFileExtensions": [  
  3.     "ts",  
  4.     "tsx",  
  5.     "js"  
  6.   ],  
  7.   "transform": {  
  8.     "^.+\\.(ts|tsx)$""ts-jest"  
  9.   },  
  10.   "testMatch": [  
  11.     "**/src/**/*.test.+(ts|tsx|js)"  
  12.   ],  
  13.   "collectCoverage"true,  
  14.   "coverageReporters": [  
  15.     "json",  
  16.     "lcov",  
  17.     "text",  
  18.     "cobertura"  
  19.   ],  
  20.   "coverageDirectory""<rootDir>/jest",  
  21.   "moduleNameMapper": {  
  22.     "\\.(css|less|scss|sass)$""identity-obj-proxy"  
  23.   },  
  24.   "reporters": [  
  25.     "default",  
  26.     "jest-junit"  
  27.   ],  
  28.   "coverageThreshold": {  
  29.     "global": {  
  30.       "branches": 100,  
  31.       "functions": 100,  
  32.       "lines": 100,  
  33.       "statements": 100  
  34.     }  
  35.   }  
  36. },  
  37. "jest-junit": {  
  38.   "output""./jest/summary-jest-junit.xml"  
  39. }  

Add Tests to SPFx WebPart

 
In Visual Studio Code, follow below steps to add some tests to our SPFx solution.
 
Add “test” folder under “src\webparts\spFxTest\”.
 
Under “test” folder, add a file “basic.test.ts”.
  1. /// <reference types="jest" />  
  2.   
  3. import * as React from 'react';  
  4. import { configure, mount, ReactWrapper } from 'enzyme';  
  5. import * as Adapter from 'enzyme-adapter-react-16';  
  6.   
  7. configure({ adapter: new Adapter() });  
  8.   
  9. import SpFxTest from '../components/SpFxTest';  
  10. import { ISpFxTestProps } from '../components/ISpFxTestProps';  
  11.   
  12. describe('Enzyme basics', () => {  
  13.   
  14.   let reactComponent: ReactWrapper<ISpFxTestProps, {}>;  
  15.   
  16.   beforeEach(() => {  
  17.   
  18.     reactComponent = mount(React.createElement(  
  19.       SpFxTest,  
  20.       {  
  21.         description: "SPFx Test"  
  22.       }  
  23.     ));  
  24.   });  
  25.   
  26.   afterEach(() => {  
  27.     reactComponent.unmount();  
  28.   });  
  29.   
  30.   it('should root web part element exists', () => {  
  31.   
  32.     // define the css selector  
  33.     let cssSelector: string = '#spfxTest';  
  34.   
  35.     // find the element using css selector  
  36.     const element = reactComponent.find(cssSelector);  
  37.     expect(element.length).toBeGreaterThan(0);  
  38.   });  
  39.   
  40.   it('should has the correct title', () => {  
  41.     // Arrange  
  42.     // define contains/like css selector  
  43.     let cssSelector: string = 'h1';  
  44.   
  45.     // Act  
  46.     // find the element using css selector  
  47.     const text = reactComponent.find(cssSelector).text();  
  48.   
  49.     // Assert  
  50.     expect(text).toBe("SPFx Test webpart");    
  51.   });  
  52. });  

Run Test Cases

 
On the command prompt and run the below command to execute the test cases.
  1. npm test  
 

Summary

 
Unit test helps to develop new functionalities by ensuring the integrity of the existing functionality. Unit tests for SPFx solutions can be developed using Jest JavaScript Testing Framework.