1. ホーム
  2. javascript

[解決済み] jest でエクスポートされた const をモックする方法

2022-10-04 19:39:12

質問

エクスポートされた const 変数に依存しているファイルがあります。この変数には true に設定されていますが、必要であれば false を手動で設定し、下流のサービスが要求した場合の動作を防ぐことができます。

をモック化する方法がよくわかりません。 const をテストするためにその値を変更できるように Jest でモックする方法がわかりません。 truefalse の条件を満たしている必要があります。

//constants module
export const ENABLED = true;

//allowThrough module
import { ENABLED } from './constants';

export function allowThrough(data) {
  return (data && ENABLED === true)
}

// jest test
import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';

describe('allowThrough', () => {
  test('success', () => {
    expect(ENABLED).toBE(true);
    expect(allowThrough({value: 1})).toBe(true);
  });

  test('fail, ENABLED === false', () => {
    //how do I override the value of ENABLED here?

    expect(ENABLED).toBe(false) // won't work because enabled is a const
    expect(allowThrough({value: 1})).toBe(true); //fails because ENABLED is still true
  });
});

どのように解決するのですか?

この例は、ES6モジュールの構文をES5にコンパイルする場合に動作します。なぜなら、最終的にすべてのモジュールのエクスポートは同じオブジェクトに属し、変更することができるからです。

import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';
import * as constants from './constants';

describe('allowThrough', () => {
    test('success', () => {
        constants.ENABLED = true;

        expect(ENABLED).toBe(true);
        expect(allowThrough({ value: 1 })).toBe(true);
    });

    test('fail, ENABLED === false', () => {
        constants.ENABLED = false;

        expect(ENABLED).toBe(false);
        expect(allowThrough({ value: 1 })).toBe(false);
    });
});

また、生のcommonjsに切り替えることもできます。 require 関数の助けを借りて、次のようにすることもできます。 jest.mock(...) :

const mockTrue = { ENABLED: true };
const mockFalse = { ENABLED: false };

describe('allowThrough', () => {
    beforeEach(() => {
        jest.resetModules();
    });

    test('success', () => {
        jest.mock('./constants', () => mockTrue)
        const { ENABLED } = require('./constants');
        const { allowThrough } = require('./allowThrough');

        expect(ENABLED).toBe(true);
        expect(allowThrough({ value: 1 })).toBe(true);
    });

    test('fail, ENABLED === false', () => {
        jest.mock('./constants', () => mockFalse)
        const { ENABLED } = require('./constants');
        const { allowThrough } = require('./allowThrough');

        expect(ENABLED).toBe(false);
        expect(allowThrough({ value: 1 })).toBe(false);
    });
});