coinpayu

   Testing is an important phase of all software development lifecycle. It should be a part of continuous development and achieve better results. SharePoint Framework is no exception to this. In this article we can learn initial setup for SPFx unit testing using Jest and Enzyme.

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 command prompt and create a new Directory


  1. md spfx-react-unit-test 

Navigate to the created directory


  1. cd spfx-react-unit-test 

Run the Yeoman SharePoint Generator to create the SPFx solution.


  1. yo @microsoft/sharepoint 

Yeoman generator will present you with the wizard by asking questions about the solution to be created.


Solution Name: Hit Enter to have default name (spfx-react-unit-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: default(Enter)

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

It's take some time to create scaffold. Once the scaffolding process is completed it will ready to add jest in this SPFx for default HelloWorld Component.

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\helloWorld\components\HelloWorld.tsx” to execute the test cases against.
 
 
import * as React from 'react';
import styles from './HelloWorld.module.scss';
import { IHelloWorldProps } from './IHelloWorldProps';
import { escape } from '@microsoft/sp-lodash-subset';

export default class HelloWorld extends React.Component<IHelloWorldProps, {}> {
  public render(): React.ReactElement<IHelloWorldProps> {
    return (
      <div id={'HelloWorld'} className={styles.helloWorld}>
        <div className={styles.container}>
          <div className={styles.row}>
            <div className={styles.column}>
              <span className={styles.title}>Welcome to SharePoint!</span>
              <p className={styles.subTitle}>Customize SharePoint experiences using Web Parts.</p>
              <p className={styles.description}>{escape(this.props.description)}</p>
              <a href="https://aka.ms/spfx" className={styles.button}>
                <span className={styles.label}>Learn more</span>
              </a>
            </div>
          </div>
        </div>
      </div>
    );
  }
}


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” or you can add new script seperately for both gulp and jest like below.
 


Jest Configurations

In newer version of SPFx, There are lot of issues generating during the test. To acheive this setup without error do below,

Add below mentioned config files in your project root folder,

1. Jest Config File
 
// jest.config.js

module.exports = {
    preset'ts-jest',

    // Test spec file resolution pattern
    // Matches parent folder `__tests__` and filename
    // should contain `test` or `spec`.
    testRegex"(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",

    moduleFileExtensions: ["js""jsx""ts""tsx"],
    moduleDirectories: ["node_modules"],
    moduleNameMapper: {
        "\\.(css|scss|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|html)$""identity-obj-proxy",
        "office-ui-fabric-react/lib/(.)$""office-ui-fabric-react/lib-commonjs/$1"
    },
    transform: {
        "^.+\\.[t|j]sx?$""babel-jest",
    },
    testPathIgnorePatterns: [
        "<rootDir>/lib",
    ],
    transformIgnorePatterns: [
        "/node_modules/",
        "node_modules/(?!(@microsoft/sp-core-library))",
        "node_modules/?!(@microsoft/sp-http)"
    ],
    coveragePathIgnorePatterns: [
        "/__tests__/",
        "node_modules"
    ],
    collectCoveragetrue,
    coverageReporters: [
        "json",
        "lcov",
        "text",
        "cobertura"
    ],
    coverageDirectory"<rootDir>/jest",
    reporters: [
        "default",
        "jest-junit"
    ],
    coverageThreshold: {
        "global": {
            "branches"100,
            "functions"100,
            "lines"100,
            "statements"100
        }
    },
    // Setup Enzyme
    "snapshotSerializers": ["enzyme-to-json/serializer"],
    "setupFilesAfterEnv": ["<rootDir>/setupEnzyme.ts"],
};

2.  Babel config file

// babel.config.js

module.exports = {
    presets: [['@babel/preset-env', { targets: { node'current' } }],
        '@babel/preset-typescript'],
};
 

3. Babelrc
 
// .babelrc

{
    "presets": ["@babel/react""@babel/env"],
    "compact" : true
}
 
 
4. setupEnzyme.ts file for accessing Enzyme adapter commonly
 
// setupEnzyme.ts

/// <reference types="jest" />
import { configure } from 'enzyme';
import * as ReactSixteenAdapter from 'enzyme-adapter-react-16';
const adapter = ReactSixteenAdapter as any;
configure({ adapternew adapter.default() });

 
Now you should add some additional packages for babel and jest working fine

  1. npm install enzyme-to-json @babel/preset-env @babel/preset-typescript @babel/preset-react --save-dev --save-exact  
 
 

Add Tests to SPFx WebPart


In Code Editor, follow below steps to add some tests to our SPFx solution.

Add “__tests__” folder under “src\webparts\helloWorld\”.

Under “__tests__” folder, add a file “HelloWorld.test.ts”. 
 
/// <reference types="jest" />

import * as React from 'react';
import { mount, ReactWrapper } from 'enzyme';

import HelloWorld from '../components/HelloWorld';
import { IHelloWorldProps } from '../components/IHelloWorldProps';

describe('Enzyme basics', () => {
  let reactComponent: ReactWrapper<IHelloWorldProps, {}>;

  beforeEach(() => {
    reactComponent = mount(
      React.createElement(HelloWorld, {
        description'SPFx Test',
      })
    );
  });

  afterEach(() => {
    reactComponent.unmount();
  });

  it('should root web part element exists', () => {
    // define the css selector
    let cssSelector: string = '#HelloWorld';

    // find the element using css selector
    const element = reactComponent.find(cssSelector);
    expect(element.length).toBeGreaterThan(0);
  });
});


Run Test Cases

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

  1. npm jest


Conclusion

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 TypeScript Testing Framework.

Hope this article is helpfull to you. Thanks to read.