- 投稿日:
関数の仮引数にthis
が入っているタイプの奴。FastifyのsetErrorHandlerに渡す関数のテストをする時に詰まったので書いておく。滅多に遭遇しないケースだと思う。
確認環境
Env | Ver |
---|---|
jest | 29.7.0 |
typescript | 5.3.3 |
実装コード
export class HogeServer {
constructor() {
console.log();
}
}
interface HogeServerInstance {
setErrorHandler(
handler: (
this: HogeServer,
error: unknown,
callback: (code: number) => void
) => void
): HogeServer;
}
// 型定義にthisが入っていてテスト時に上手くいかない
// const handle: (this: HogeServer, error: unknown, callback: (code: number) => void) => void
type HandlerFunc = Parameters<HogeServerInstance['setErrorHandler']>[0];
export const handle: HandlerFunc = (err, cb) => {
if (err instanceof Error) {
cb(500);
} else {
cb(200);
}
};
export const fuga = (s: HogeServerInstance) => {
s.setErrorHandler(handle);
};
テストコード
import { HogeServer, handle } from '.';
describe('handle', () => {
it('errがErrorインスタンスの時', () => {
const thisMock = {} as unknown as HogeServer;
const err = new Error('error-hoge');
const cbFn = jest.fn();
// .call()を使うことでthis付きで呼び出せる
handle.call(thisMock, err, cbFn);
expect(cbFn).toHaveBeenCalledWith(500);
});
it('errがErrorインスタンスではない時', () => {
const thisMock = {} as unknown as HogeServer;
const err = 1234;
const cbFn = jest.fn();
handle.call(thisMock, err, cbFn);
expect(cbFn).toHaveBeenCalledWith(200);
});
});
- 投稿日:
親クラスをモックして子クラスの単体テストをしたいときに
確認環境
Env | Ver |
---|---|
@swc/cli | 0.1.65 |
@swc/core | 1.3.105 |
@swc/jest | 0.2.31 |
@types/jest | 29.5.11 |
jest | 29.7.0 |
typescript | 5.3.3 |
サンプルコード
コードのフルセットは以下
https://github.com/Lycolia/typescript-code-examples/tree/main/mocking-base-class-with-extension-class-swc-ts
ディレクトリ構成
src
├─BaseClass
│ └─index.ts
└─ChildrenClass
├─index.ts
└─index.spec.ts
src/BaseClass/index.ts
親クラス。この例は抽象クラスだが別に具象クラスでも何でもいいと思う
export abstract class BaseClass {
constructor(
private baseValue: string,
private ctx: { [key: string]: unknown }
) {}
public hoge<ResultT>(payload: { [key: string]: unknown }) {
// テスト走行時には全て無効な値を流し込むため
// それらの影響で落ちないことの確認のために、オブジェクトの子を意図的に書いている
console.log(this.baseValue, this.ctx.hoge, payload.piyo);
// サンプルコードなので戻り値はスタブ
return {} as ResultT;
}
}
src/ChildrenClass/index.ts
子クラス
import { BaseClass } from '../BaseClass';
export class ChildrenClass extends BaseClass {
constructor(baseValue: string, ctx: { [key: string]: unknown }) {
super(baseValue, ctx);
}
public piyo<ResultT>(payload: { [key: string]: unknown }) {
try {
// このsuper.hoge()をモックして、
// catchの中に流れるかどうかを確認するのが目的
return super.hoge<ResultT>(payload);
} catch (err) {
// 実際はロガーが動くような部分だが、サンプルコードのためconsole.logで代用する
console.log(err);
throw err;
}
}
}
src/ChildrenClass/index.spec.ts
子クラスのテスト
import { ChildrenClass } from '.';
import { BaseClass } from '../BaseClass';
describe('fetch', () => {
it('親のfetchが呼ばれ、親の戻り値が返ってくること', () => {
// 子が正しくreturnしてくるかどうかを確認するための値
const expected = { code: 200 };
// Class.prototypeとやるとモック出来る
const spiedSuperFetch = jest
.spyOn(BaseClass.prototype, 'hoge')
.mockReturnValue(expected);
// 親クラスの処理はモックするので適当な値を入れておく
// この内容が実行されていればテストが落ちるのでテストコードが間違っていることの検証に使える
const inst = new ChildrenClass('aaaa', {} as { [key: string]: unknown });
const actual = inst.piyo({ foo: 123 });
// 親クラスのメソッドが正しい引数で呼ばれたことの確認
expect(spiedSuperFetch).toHaveBeenCalledWith({ foo: 123 });
// 子クラスのメソッドの戻り値が正しいことの確認
expect(actual).toStrictEqual(expected);
});
it('親のfetchで例外が出たときに、ログ出力とリスローがされること', () => {
const expected = Error('ERR');
// 親クラスのメソッドが例外をスローするケースを作る
jest.spyOn(BaseClass.prototype, 'hoge').mockImplementation(() => {
throw expected;
});
// catch句の中でロガーが動いているかどうかの検査用
const spiedConsoleLog = jest.spyOn(console, 'log');
const inst = new ChildrenClass('aaaa', {} as { [key: string]: unknown });
// 例外がリスローされていることを確認
expect(() => {
inst.piyo({ foo: 123 });
}).toThrow(expected);
// ロガーが動いていることを確認
expect(spiedConsoleLog).toHaveBeenCalled();
});
});
- 投稿日:
以下のようなコードを書いたときにmockFnにイベント引数が渡らないが、これをどうにかして取る方法。結論から言うとまともに取れないが、試行錯誤した時のログとして残しておく
const mockFn = jest.fn();
render(<input onChange={mockFn} />);
fireEvent.change(inputElement, { target: { value: 'aaa' } });
確認環境
Env | Ver |
---|---|
@swc/core | 1.3.66 |
@swc/jest | 0.2.26 |
@testing-library/jest-dom | 5.16.5 |
@testing-library/react | 14.0.0 |
jest | 29.5.0 |
react | 18.2.0 |
サンプルコード
これは以下のように書くとfireEvent
の第二引数で指定したtarget.value
の部分だけは一応取れる。
理由としてはfireEvent
がelement.dispatchEvent
を読んでいると思われるためだ。余り深くは追っていないが、react-testing-libraryの実装上は多分そうなっていると思われる。
import { fireEvent, render } from '@testing-library/react';
it('test', () => {
const mockFn = jest.fn((ev) => {
console.log(ev);
});
const { container } = render(<input id="hoge" onChange={mockFn} value={'a'} />);
const element = container.querySelector('input');
if (element === null) throw new Error();
element.dispatchEvent = jest.fn();
fireEvent.change(element, {
target: {
value: 'bbb'
}
});
expect(element.dispatchEvent.mock.instances[0].value).toBe('bbb');
});
- 投稿日:
ESM化が叫ばれて久しいですが、未だにJestはESMとCJSが混在したコードを処理してくれません。
Getting StartedにもSWCに対する言及がないので、きっともう忘れられているのでしょう。swc-project/jestの方も特にやる気はなさそうだし、やりたければ自分でPR書きましょうって感じだと思います。きっと。
確認環境
node_modules配下にESMで作られたモジュールが存在し、コードはTypeScript、トランスパイルにはSWCを利用する。
Env | Ver |
---|---|
@swc/cli | 0.1.62 |
@swc/core | 1.3.92 |
@swc/jest | 0.2.29 |
@swc/register | 0.1.10 |
jest | 29.7.0 |
typescript | 5.2.2 |
やったけど意味がなかったこと
package.json
のtype
をmodule
にするjest.config.js
のtransformIgnorePatterns
にESMモジュールのパスだけ除外する設定を書く- 上記に加えて
transform.jsc.path
にpkg-name: ['node_modules/pkg-name']
を追記する node --experimental-vm-modules node_modules/jest/bin/jest.js
で実行する- 多少マシになったがコケるものはコケる
- ESMで書かれたモジュールを丸ごとモックする
- 一切効果なし
所感
多分Webpackでバンドルしてnode_modules
の中身も外も関係ない状態にするのが一番無難なのではないかと思いました。
Node.jsの組み込みテストランナーにすれば解決するかな?と思ったものの、こちらは現状SWCでは使えそうにないので諦めました。
参考までに以下のコマンドで走らさせられます。
node --require @swc/register --test ./src/**/*.spec.ts
取り敢えずESMに引っかったモジュールはCJS時のバージョンを維持しておくことにしましたが、このままだとSWC使えないし、なんとかなって欲しいですね。Webpack使えば解決できるのはわかるんですが、このために使いたくないので、テストを重視する場合、Vitestを持つViteが有力候補になって来そうです。
2024-02-17追記
esbuild + Node.js built-in test runnerの組み合わせであればテストはできるが肝心の実行ができず無意味だった
- 投稿日:
本記事ではTypeScriptとSWC、Jestの組み合わせ環境でjest.spyOn
を使う方法をexport
パターン別に書いていきます。また、jest.spyOn
対象の実装の詳細はテストせず、モック化したインターフェースのテストのみを行う前提で書いています。
確認環境
Env | Ver |
---|---|
Node.js | 18.14.0 |
typescript | 4.9.5 |
@swc/cli | 0.1.62 |
@swc/core | 1.3.36 |
@swc/jest | 0.2.24 |
jest | 29.4.3 |
サンプルコード
全編は以下にあります
jest.spyOn pattern example for SWC + TypeScript
親関数から子関数を呼び出すパターンで、子関数のjest.spyOn
をするシチュエーションで考えます。
default export編
以下のdefaultエクスポートをjest.spyOn
する方法です。
child.ts
export const child = (param: string) => {
return param;
};
parent.ts
import child from 'src/default/child';
const parent = (param: string) => {
return child(param);
};
export const Parent = {
parent,
};
parent.spec.ts
この形式の場合import
側では書き換え不能なのでファイルごとモックにして解決します。
このやり方はファイルごとモックするため、同じファイルにある関数をjest.spyOn
するのには向いていません。
import * as child from 'src/default/child';
import { Parent } from 'src/default/parent';
jest.mock('src/default/child');
describe('default', () => {
it('called by child function', () => {
const spiedChild = jest.spyOn(child, 'default');
Parent.parent('foo');
expect(spiedChild).toHaveBeenCalledWith('foo');
});
});
named export編
以下の名前付きエクスポートをjest.spyOn
する方法です。
child.ts
export const child = (param: string) => {
return param;
};
parent.ts
import { child } from 'src/named-export/child';
export const parent = (param: string) => {
return child(param);
};
parent.spec.ts
default exportと同じくimport
側では書き換え不能なのでファイルごとモックにして解決します。
このやり方はファイルごとモックするため、同じファイルにある関数をjest.spyOn
するのには向いていません。
import * as child from 'src/named-export/child';
import { parent } from 'src/named-export/parent';
jest.mock('src/named-export/child');
describe('function', () => {
it('called by child function', () => {
const spiedChild = jest.spyOn(child, 'child');
parent('foo');
expect(spiedChild).toHaveBeenCalledWith('foo');
});
});
namespace export編
やり方はnamed export編と同じです。
child.ts
export namespace Child {
export const child = (param: string) => {
return param;
};
}
parent.ts
import { Child } from 'src/namespace/child';
export namespace Parent {
export const parent = (param: string) => {
return Child.child(param);
};
}
parent.spec.ts
namespaceの場合、トランスパイル後にクロージャになり、書き換え以前に関数にアクセスできなくなるため、ファイルごとモックにして解決します。
このやり方はファイルごとモックするため、同じファイルにある関数をjest.spyOn
するのには向いていません。
import { Child } from 'src/namespace/child';
import { Parent } from 'src/namespace/parent';
jest.mock('src/namespace/child');
describe('namespace', () => {
it('called by child function', () => {
const spiedChild = jest.spyOn(Child, 'child');
Parent.parent('foo');
expect(spiedChild).toHaveBeenCalledWith('foo');
});
});
module export編
これだけやり方が変わります。
child.ts
const child = (param: string) => {
return param;
};
export const Child = {
child,
};
parent.ts
import { Child } from 'src/module/child';
const parent = (param: string) => {
return Child.child(param);
};
export const Parent = {
parent,
};
parent.spec.ts
このケースの場合オブジェクトをexport
していて書き換えができるため、モック化せずにそのままjest.spyOn
することが出来ます。
このやり方であれば、ファイルのモックはしないため、同じファイルにある関数をjest.spyOn
する事ができますが、裏を返せばオブジェクトの書き換えが可能であるため、実装方法によっては予期せぬ不具合が生まれる可能性があり、危険です。
何かしらの悪意ある攻撃を受けた場合にオブジェクトがすり替わるなどすると致命的だと思います。
import { Child } from 'src/module/child';
import { Parent } from 'src/module/parent';
describe('module', () => {
it('called by child function', () => {
const spiedChild = jest.spyOn(Child, 'child');
Parent.parent('foo');
expect(spiedChild).toHaveBeenCalledWith('foo');
});
});
おまけ:それぞれのトランスパイル結果
.spec.js
は省いてます
default export編
child.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'default', {
enumerable: true,
get: () => _default,
});
const child = (param) => {
return param;
};
const _default = child;
parent.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'Parent', {
enumerable: true,
get: () => Parent,
});
const _child = /*#__PURE__*/ _interopRequireDefault(require('./child'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
const parent = (param) => {
return (0, _child.default)(param);
};
const Parent = {
parent,
};
named export編
child.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'child', {
enumerable: true,
get: () => child,
});
const child = (param) => {
return param;
};
parent.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'parent', {
enumerable: true,
get: () => parent,
});
const _child = require('./child');
const parent = (param) => {
return (0, _child.child)(param);
};
namespace export編
child.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'child', {
enumerable: true,
get: () => child,
});
const child = (param) => {
return param;
};
parent.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'Parent', {
enumerable: true,
get: () => Parent,
});
const _child = require('./child');
var Parent;
(function (Parent) {
var parent = (Parent.parent = (param) => {
return _child.Child.child(param);
});
})(Parent || (Parent = {}));
module export編
child.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'Child', {
enumerable: true,
get: () => Child,
});
const child = (param) => {
return param;
};
const Child = {
child,
};
parent.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
Object.defineProperty(exports, 'Parent', {
enumerable: true,
get: () => Parent,
});
const _child = require('./child');
const parent = (param) => {
return _child.Child.child(param);
};
const Parent = {
parent,
};
この記事を書いた切っ掛け
一言でいうとTSC(TypeScript Compiler) からSWCに移行した際にjest.spyOn
を使ったら、上手く使えずにハマったためです。
まずTypeScript + JestではTypeScriptをCJS(CommonJS) にトランスパイルするためjest.spyOn
が有効でした。しかし、SWCはTypeScriptをESM(ES Modules) にトランスパイルします。ESMではjest.spyOn
が有効になりません。
これはCJSではexport
したObjectの書き換えが可能なのに対し、ESMでは出来ないためです。(jest.spyOn
は実行時にオブジェクトを書き換えることで動いています)
この対策としてファイルそのものをモックに置き換えることで、jestの管理下に起き、自由に書き換えられるようにするのが本記事のアプローチです。以前と異なり、呼び出している関数の実装の詳細を見ることはできなくなりましたが、これは単体テストの観点としては正しいため、ある意味本来の単体テストになったとも取れると考えています。(モックに元の処理を注入することで今まで通り実装の詳細を確認することも出来る可能性がありますが、確認してません)