LoginSignup
6
3

More than 5 years have passed since last update.

スナップショットテストを使いPublicなAPIをテストする

Last updated at Posted at 2017-11-07

ライブラリを書いていると、公開するAPIのスキーマをテストしたいことがあります。

例えば、以下のような非常に小さなライブラリ。

const hello = 'hello'

module.exports = name => {
  return `${hello} ${name}`
}

module.exports.first = 1
module.exports.noop = () => {}

ここで、公開されているAPIは、module.exportsで公開したFunctionfirstnoopです。
しかし、APIを変更する必要が出て、firstを以下のようにnumberからfunctionへと変更したとします。

module.exports.first = () => 1

もちろんそれぞれにユニットテストを書くのは重要ですが、スキーマがあると安心です。
jestをインストールし、以下のようなコードを用意します。

yarn add --dev jest
test('public API snapshot', () => {
  const api = require('.')
  const schema = Object.keys(api).reduce(
    (acc, k) => ({ ...acc, [k]: typeof api[k] }),
    { 'module.exports': typeof api }
  )
  expect(schema).toMatchSnapshot()
})

これで、module.exportsによって公開されたスキーマのスナップショットを取ることができます。
例えば、上記のようにnumberからfunctionへと公開するAPIが変わったら以下のようにFailします。

スクリーンショット 2017-11-08 07.01.22.png

もちろん、新しいAPIを公開したときもFailします。

module.exports.second = () => 2

スクリーンショット 2017-11-08 07.11.12.png

これによって、カバレッジを見るまでもなく、テストすべき関数がひと目でわかります。また、バージョニングの指標の一つになるでしょう。(コミットメッセージによるセマンティックリリースはあくまで人間の手よる手動管理という認識です)

終わりに

荒削りですが、以上です。
何か議論があればコメント欄またはTwitterまでお願いします。

6
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3