検索条件
	タグで絞り込み
		Node.js(8)
		Node.js::Jest(8)
		ソフトウェア(1)
		ソフトウェア::Docker(1)
		ライブラリ(5)
		ライブラリ::React(5)
		言語(8)
		言語::TypeScript(8)
		開発::テスト(9)
		開発::自動化(1)
	
	
	全10件
	(2/2ページ)
	
	
fsとかchild_processとかそういうやつをモックする方法
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');
  });
});
スプレッド演算子で引き渡した内容の内、一部だけを利用するケースを想定
type FooBar = {
  foo: string;
  bar: number;
};
/**
 * `foo` と `bar` しか使われない関数
 * @param arg
 */
export const spreadExample = (arg: FooBar) => {
  return new Promise((resolve) => {
    resolve([arg.foo, arg.bar]);
  });
};
import * as spex from '../spreadExample';
const spiedSpreadExample = jest.spyOn(spex, 'spreadExample');
describe('spreadExample', () => {
  it('example', async () => {
    const test = {
      foo: 'hoge',
      bar: 123,
      baz: true, // 今回の課題となる項目
    };
    // 余計な `baz` が流し込まれているため、
    // 普通に検査しようとすると `baz` が邪魔で上手く行かないケース
    await spex.spreadExample({ ...test });
    expect(spiedSpreadExample).toBeCalled();
    // コールバックで `expect.objectContaining()` を呼ぶことにより
    // 見たい項目だけを検査することが可能(`baz` を見なくて済む
    expect(spiedSpreadExample).toHaveBeenCalledWith(
      expect.objectContaining({
        foo: 'hoge',
        bar: 123,
      })
    );
  });
});
単体テストの観点でいうとprocess.argvそのものはモックしないほうが良いと思っているので、本記事ではprocess.argv自体をモックする方法と、それを回避する方法を紹介する
describe('example', () => {
  afterEach(() => {
    // 元に戻しておく
    process.argv.length = 2;
  });
  it('got first param', () => {
    process.argv.push('param1');
    expect(process.argv.length).toBe(3);
    expect(process.argv[2]).toBe('param1');
  });
});
process.argvを利用している関数でprocess.argvを引数に取ればモック不要となる
const getArgv = (argv: string[]) => {
    // some procedure
}
describe('getArgv', () => {
  it('got first param', () => {
    const argv = [,, 'param1'];
    expect(argv.length).toBe(3);
    expect(argv[2]).toBe('param1');
  });
});
runコマンドでサービスを指定してコマンドを蹴ると実行結果が取れる
docker-compose run node-git 'npm' 't'docker-compose run node-git 'sh' '-c' '"ls -la && grep foo"'