0
0

More than 1 year has passed since last update.

【Tips】Typescript+Jestでconfigモジュールをモック化する

Posted at

はじめに

Typescript+Jestのモックはめちゃくちゃ便利な反面、色々なモック化のパターンがあって分かりにくい(自分がちゃんとTypescriptを理解しきれていないからなのだろうけど)。
今回、configモジュールをモック化する際に苦戦したので、方法をまとめておく。

テストコード

以下のようにすれば問題なく動作するが、config.has()は動作だけしてくれればよいのに実装しなければいけないのがイケていない。公式ドキュメントの「部分的なモック」の通りにやっても上手くいかない(jest.resetAllMocks()が悪さをしているような気がするが、clearAllMocks()にするとそれはそれで他の場所で不都合があった)。何か良い方法はないものか。

import { describe, test, jest, afterEach } from '@jest/globals';
import config from 'config';

jest.mock('config');
const configMock = config as jest.Mocked<typeof config>; // configのモック化

describe('Config Test Suite', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  test('Test Pattern 1', () => {
    // モック対象外は元の情報を使いたいので、requireActual()で元の情報をロードしておく
    const originalConfig: any = jest.requireActual('config');
    // モック化したconfigでget()の実装
    configMock.get.mockImplementation((key: string) => {
      // 特定のキーが指定された場合のみ上書きしてreturn
      if (key === 'testKey') return 'testValue';
      return originalConfig.get(key);
    });
    // プロダクトコードでhas()を使っている場合はhas()も実装しておく
    configMock.has.mockImplementation((key: string) => {
      return originalConfig.has(key);
    });

    // 以下、assertionを書いていく
  });
});
0
0
0

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
0
0