golangの日記

Go言語を中心にプログラミングについてのブログ

TypeScript jest exportしていない関数・変数のテスト

typescript.png


エクスポートしていない関数・変数 や class のプライベート関数・変数のテスト方法





目次



エクスポートしていない変数・関数のテスト


index.ts

const Message = 'hello';



オブジェクトを使う


オブジェクトにエクスポートしてない変数・関数をセットして export !
これでも良いけど「結局 export すんのかよ」となるので他の方法を探すことになる。


index.ts

const Message = 'hello';

export const __local__ = {
    Message,
};


index.test.ts

import {__local__} from './index';

test('__local__.Message', () => {
    expect(__local__.Message).toBe('hello');
});



rewire を使う


$ yarn add --dev rewire @types/rewire

# rewire を TypeScript で使うのに必要なので
# ts-node をインストールしてなければ yarn add --dev ts-node する


index.test.ts

import rewire from 'rewire';

const __local__ = rewire('./index.ts');

test('Message', () => {
    expect(__local__.__get__('Message')).toBe('hello');
});


package.json

"scripts": {
    "test": "ts-node node_modules/jest/bin/jest.js"
}

/*
  tsconfig.json の module が commonjs でなければ -O オプションで指定する。
  "test": "ts-node -O '{\"module\":\"commonjs\"}' node_modules/jest/bin/jest.js"
*/


あとは実行するだけ

$ npm test



クラスのプライベート変数・関数のテスト


index.ts

export class Hello {
    protected protected_method(): string {
        return 'protected!';
    }

    private private_method(): string {
        return 'private!';
    }
}


index.test.ts

連想配列のように h['key'] するか、クラスのインスタンスを any 型にすると private/protected でも呼び出せる


import {Hello} from './index';

test('test private/protected method', () => {
    const h = new Hello();

    // オブジェクトと同じように呼び出す
    expect(h['private_method']()).toBe('private!');

    // any 型にアサーションする
    expect((h as any).protected_method()).toBe('protected!');
});