Jestによるデータ駆動ユニットテスト


Photo by Markus Spiske on Unsplash


データ駆動単体テストは、入力データの範囲でテストを実行する簡単で効率的な方法です.このような状況で役に立つことができます
  • より広い範囲の価値に対するテスト
  • NULLと未定義値のテスト
  • 例えば、日付(月の始まり、月の終わり、…)のために、エッジケースに対するテスト
  • または、各テスト行が別のテストとしてカウントされるため、あなたのユニットのテストの統計情報を微調整する.あなたのマネージャーは感銘を受けます.😉

  • 簡易サンプル
    数がそうであるかどうかチェックする簡単なテストを定義しましょう:
    it('should be even', () => {
        expect(2 % 2).toBe(0);
    });
    
     ✓ is even
    
    一連の数をチェックするために、我々はJestのit.each (or test.each , 以来ittest ). 入力データを配列として渡し、各項目を個別にテストしますn ).
    it.each([2,4,6])('should be even', (n) => {
        expect(n % 2).toBe(0);
    });
    
    ✓ should be even
    ✓ should be even
    ✓ should be even
    
    私たちはseveral predefined トークンはテストの名前を改善するため、失敗したテストを見つけやすくなります.
    it.each([2,4,5,6])('%i should be even', (n) => {
        expect(n % 2).toBe(0);
    });
    
    ✓ 2 should be even
    ✓ 4 should be even
    ✕ 5 should be even
    ✓ 6 should be even
    

    複数のパラメータ
    あなたのテストにも複数のパラメータを渡すことができます.次のサンプルでは、期待値をテストに渡します.
    it.each([[2,4], [6,36], [8,64]])('can square %i to %s', (n, expected) => {
        expect(n*n).toBe(expected);
    });
    
    ✓ can square 2 to 4
    ✓ can square 6 to 36
    ✓ can square 8 to 64
    
    入力テーブルは配列の配列として定義されます.各内部配列は、入力テーブルの1行です.
    私はテストがよく読めるように、理解し、明確に意図している.フォーカスは実際のテストではなく、実装でなければなりません.JESTは、厳密にサポートする構文を提供します.
    it.each`
          n     | expected
          ${1}  | ${1}
          ${2}  | ${4}
          ${4}  | ${16}
          ${12} | ${144}
        `('can square $n to $expected', ({ n, expected }) => {
                expect(n*n).toBe(expected);
    });
    
    ✓ can square 1 to 1
    ✓ can square 2 to 4
    ✓ can square 4 to 16
    ✓ can square 12 to 144
    
    入力テーブルは、実際のテーブルのようになります.最初の行がパイプで区切られた変数名を含むテンプレート文字列として定義されます| . 次の行は、テストを実行するために入力データの1つの組み合わせであり、テンプレートリテラル式として定義されます.
    テスト名の中で変数名を参照することができます$variable .

    複数のテストを実行する.each も利用可能ですdescribe -ブロックは、複数のテストを実行したり、テストデータのセットに対しても全体のテストスイートを簡単になります.
    describe.each`
        x     | y
        ${10} | ${2}
        ${9}  | ${3}
        ${8}  | ${4}
    `('With x=$x and y=$y', ({x, y}) => {
        it('x should be larger then y', () => {
            expect(x).toBeGreaterThan(y);
        });
    
        it('should x should by dividable by y without rest', () => {
            expect(x % y).toBe(0);
        });
    });
    
    With x=10 and y=2
        ✓ x should be larger then y
        ✓ should x should by dividable by y without rest
    With x=9 and y=3
        ✓ x should be larger then y (1ms)
        ✓ should x should by dividable by y without rest
    With x=8 and y=4
        ✓ x should be larger then y
        ✓ should x should by dividable by y without rest (1ms)
    
    あなたも、組み合わせることができますdescribe.each and it.each , しかし、理解力に目を向けてください.