Jestで非公開関数をテストしたい

rewire を使うと簡単にできた。

github.com

前提

Jest入ってる。Babel入れてない。

インストール

npm install --save-dev rewire

準備

通常なら require(path) とするところを rewire(path) にする

const rewire = require('rewire')
const myModule = rewire('./myModule')

テスト対象の関数を取り出してテストする

const myPrivateFunc = myModule.__get__('myPrivateFunc');
expect(myPrivateFunc()).toEqual({})