鍋綿ブログ

C#・SharePoint・SharePoint Framework・Office365を中心に扱うブログです。

SharePoint Frameworkでユニットテスト

SharePoint Frameworkでユニットテストを書こうと思った時に調べたことをまとめておきます。

 

 

ツール

公式サイトでの案内通り、Jestを利用します。

コードサンプル

テスト用プロジェクトの作成から行っていきます。開発環境の構築がまだの方は以下の記事で構築方法を紹介しましたので参考にしてください。

SharePoint Framework (SPFx) 開発環境構築 (Windows 10) - 鍋綿ブログ

テスト用プロジェクト作成

まずはプロジェクトを作成します。任意のフォルダで以下を実行します。

yo @microsoft/sharepoint

今回は以下の通りオプションを選択しました。

? What is your solution name? unit-test
? Which baseline packages do you want to target for your component(s)? SharePoint Online only (latest)
? Where do you want to place the files? Use the current folder
Found npm version 6.9.0
? Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without
running any feature deployment or adding apps in sites? No
? Will the components in the solution require permissions to access web APIs that are unique and not shared with other c
omponents in the tenant? No
? Which type of client-side component to create? WebPart
Add new Web part to solution unit-test.
? What is your Web part name? UnitTesting
? What is your Web part description? UnitTesting description
? Which framework would you like to use? React

 

 次にjestをインストールします。

npm i jest jest-junit @voitanos/jest-preset-spfx-react16 -d

 

また、configフォルダ直下にjest.config.jsonという名前で新しいファイルを作成し、以下を記述します。

{
  "preset": "@voitanos/jest-preset-spfx-react16",
  "rootDir": "../src",
  "coverageReporters": [
    "text",
    "json",
    "lcov",
    "text-summary",
    "cobertura"
  ],
  "reporters": [
    "default",
    ["jest-junit", {
      "suiteName": "jest tests",
      "outputDirectory": "temp/test/junit",
      "outputName": "junit.xml"
    }]
  ]
}

 

テストされるモジュールも作成しておきましょう。今回は例としてsrcフォルダ直下にSample.tsファイルを作成しました。

/** ユニットテスト用のサンプルクラスです。 */
export class Sample
{
    /** 足し算を行います。 */
    public Addition(arg1 : number, arg2 : number) : number
    {
        return arg1 + arg2;
    }
}

足し算のロジックがこのコードで充分かどうかは、後述のテストコードで確認します。

 

最後にテストコードを記述します。srcフォルダ配下の任意の位置に、拡張子が .spec.ts であるファイルを作成することでテストコードが認識されます。今回は例としてsrcフォルダ直下にSample.spec.tsファイルを作成しました。

import 'jest';
import { Sample } from './Sample';

describe('Sampleクラステスト', () => {
    describe('Addtitionメソッドテスト', () => {
        it('正常系テスト', () => {
            // 3 + 7 = 10 になるはずである
            expect(new Sample().Addition(3, 7)).toBe(10);
        });
        it('0値のテスト', () => {
            // 2 + 0 = 2 になるはずである
            expect(new Sample().Addition(2, 0)).toBe(2);
        });
        it('NULL値のテスト', () => {
            // 今回は4 + null = 4 という動きを期待するとしよう
            expect(new Sample().Addition(4, null)).toBe(4);
        });
        it('undefinedのテスト', () => {
            // 今回は6 + undefined = 6 という動きを期待するとしよう
            expect(new Sample().Addition(6, undefined)).toBe(6);
        });
    });
});

テストの実行

以下のコマンドでテストを実行します。

npm run test

 

今回のサンプルコードでは、undefinedのテストに失敗という結果が得られました。

f:id:micknabewata:20191118174649p:plain

引数にundefinedを入れてテストしたら失敗した

Reactコンポーネントをテストする

Webパーツなどで利用しているReactコンポーネントをテストするコードはこんな感じです。

import 'jest';
import UnitTesting from './components/UnitTesting';
import { IUnitTestingProps } from './components/IUnitTestingProps';
import styles from './components/UnitTesting.module.scss';
import * as React from 'react';
import { configure, mount, ReactWrapper } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });  

describe('UnitTestingWebPartクラステスト', () => {

    let reactComponent: ReactWrapper<IUnitTestingProps, {}>;

    beforeEach(() => {
        reactComponent = mount(React.createElement(
            UnitTesting,
            {
                description: "SPFx Test"
            }
        ));
    });

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

    describe('レンダリングテスト', () => {
        it('unitTestingクラスの要素があること', () => {
            // unitTestingクラスの要素があること
            const element = reactComponent.find(`.${styles.unitTesting}`);
            expect(element.length).toBeGreaterThan(0);
        });
    });
});

 

以上、参考になれば幸いです。