GitHub Actionでnpm testを実行する時のテスト成否の返し方

非同期処理のテスト成否の返し方

GitHub Actionsでstepで何か処理を実行した時、失敗したらエラーが表示され、全てのstepが成功したら処理終了が表示されます。この場合、stepで定義した処理の実行結果によって成否が判断されるため、非同期の処理をテストしたい場合はエラーを投げてあげる必要があります。

1. 非同期の処理

下記のような処理を用意します。

module.exports.add = function (a, b, callback) {
  callback(a + b)
  return
}

module.exports.multiply = function (a, b, callback) {
  callback(a * b)
  return
}

module.exports.devide = function (a, b, callback) {
  callback(a / b)
  return
}
2. テストコードを用意

先ほど記載したテストを試験するためのテストコードを用意します。 index.addのテストを無理やりエラーにしています。

var index = require('../index');

describe('unit test', function () {
  it('1 + 2 = 3 test', function () {
    index.add(1, 2, (result) => {
      // エラーを起こすために === 2 とする
      if (result === 2) {
        return 0
      } else {
        throw Error('1 + 2 error !!!')
      }
    })
  });

  it('1 * 2 = 2 test', function () {
    index.multiply(1, 2, (result) => {
      if (result === 2) {
        return 0
      } else {
        throw Error('1 * 2 error !!!')
      }
    })
  });

  it('1 / 2 = 0.5 test', function () {
    index.devide(1, 2, (result) => {
      if (result === 0.5) {
        return 0
      } else {
        throw Error('1 / 2 error !!!')
      }
    })
  });
});
3. テストを実行

下記のような表示になります。

番外編

2で記載したテストはassertを使っても同じです。

var assert = require('assert');
var index = require('../index');

describe('unit test', function () {
  it('1 + 2 = 3 test', function () {
    index.add(1, 2, (result) => {
      // エラーを起こすために === 2 とする
      assert.strictEqual(result, 2, '1 + 2 error !!!')
    })
  });

  it('1 * 2 = 2 test', function () {
    index.multiply(1, 2, (result) => {
      assert.strictEqual(result, 2, '1 + 2 error !!!')
    })
  });

  it('1 / 2 = 0.5 test', function () {
    index.devide(1, 2, (result) => {
      assert.strictEqual(result, 0.5, '1 + 2 error !!!')
    })
  });
});

実行結果は下記です。

assertでnpm testの結果でエラーが検知できるのはassert.strictEqual内部でthrow Errorしているからだと思います。やっていることはあまり「2. テストコードを用意」で書いたことと変わらんのではないかと思います。