マニュアルモック
マニュアルモックはモックデータを返す機能をスタブするために使用します。 例えば、ウェブサイトやデータベースのような外部リソースにアクセスする代わりに、偽のデータが使えるマニュアルモックが欲しいと考えるでしょう。 これによりテストは高速で信頼性の高いものになります。
ユーザーモジュールのモック
マニュアルモックは モジュールのディレクトリ直下の__mocks__/
サブディレクトリにモックモジュールを作成することで定義します。 例えばmodels
ディレクトリに user
と呼ばれるモジュールをモックを作成するには、 models/__mocks__
ディレクトリにuser.js
というファイルを作成して配置します。
The __mocks__
folder is case-sensitive, so naming the directory __MOCKS__
will break on some systems.
When we require that module in our tests (meaning we want to use the manual mock instead of the real implementation), explicitly calling jest.mock('./moduleName')
is required.
Node モジュールのモック
モックしようとしているモジュールが Node モジュール (例: lodash
) の場合、(ルート
フォルダをプロジェクトルート以外に設定していない限り)node_modules
ディレクトリと同階層の __mocks__
の中にモックを置くことで、モジュールは自動的にモックされます。 明示的に jest.mock('module_name')
を呼び出す必要はありません。
Scoped modules (also known as scoped packages) can be mocked by creating a file in a directory structure that matches the name of the scoped module. たとえば、@scope/project-name
という名前のスコープモジュールをモックしたいなら、@scope/
ディレクトリを作成するのに対応して、__mocks__/@scope/project-name.js
というファイルを作成します。
If we want to mock Node's built-in modules (e.g.: fs
or path
), then explicitly calling e.g. jest.mock('path')
is required, because built-in modules are not mocked by default.