お知らせ

現在サイトのリニューアル作業中のため、全体的にページの表示が乱れています。

Jestで関数の引数の一部だけexpectする

投稿日:
Node.js::Jest開発::テスト言語::TypeScript

スプレッド演算子で引き渡した内容の内、一部だけを利用するケースを想定

サンプルコード

検査対象

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,
      })
    );
  });
});