React + TypeScriptでformのonSubmitで値を取得

サンプルコード

const onSubmit = (ev: React.FormEvent<HTMLFormElement>) => {
  ev.preventDefault();
  const target = ev.target as typeof ev.target & {
    t1: { value: string };
    t2: { value: string };
  };
  console.log(target.t1.value);
  console.log(target.t2.value);
};
return (
  <div className="App">
    <form onSubmit={(ev) => onSubmit(ev)}>
      <input type="text" id="t1" />
      <input type="text" id="t2" />
      <input type="submit" />
    </form>
  </div>
);

参考

JestでNodeのコアモジュールをモックする

  • fsとかchild_processとかそういうやつをモックする方法
    • jest単体の機能では実現できないのでハマるポイント
  • たぶん jest.MockedFunction でも同じことができる

サンプルコード

import { execSync } from 'child_process';

// まず全体をモックする
jest.mock('child_process');

// モックにする
const mockExecSync = execSync as jest.MockedFunction<typeof execSync>;

describe('execSync', () => {
  it('spyOn execSync', () => {
    // 対象をコール
    execSync('echo 1');
    // 通る
    expect(mockExecSync).toHaveBeenCalled();
    // 通る, echo 2とかにするとちゃんとコケてくれる
    expect(mockExecSync).toHaveBeenCalledWith('echo 1');
  });
});