【Jest】Matcher(Assert)一覧

目次

はじめに

本記事はJestMatcher(Assert)の一覧をまとめました。

環境構築したい場合は以下の記事にまとめておりますので、是非ご参考ください。

Modifierの一覧が知りたい人は以下の記事をご覧ください。

Mockの一覧が知りたい人は以下の記事をご覧ください。

toBe(value)

toBe(value)はプリミティブな値を比較したり、オブジェクトインスタンスの参照IDを確認します。

const can = {
  name: 'pamplemousse',
  ounces: 12,
};

describe('the can', () => {
  test('has 12 ounces', () => {
    expect(can.ounces).toBe(12);
  });

  test('has a sophisticated name', () => {
    expect(can.name).toBe('pamplemousse');
  });
});

浮動小数点数にtoBeを使用しな 例えば、JavaScriptでは数値の丸めによって0.2 + 0.1と 0.3は厳密には等価ではありません。 浮動小数点がある場合は、代わりに.toBeCloseToを使用してください。

浮動小数点数にtoBeを使用しないでください。

JavaScriptでは数値の丸めによって0.2 + 0.10.3は厳密には等価ではありません。

浮動小数点がある場合は、代わりにtoBeCloseToを使用してください。

toHaveBeenCalled()

toHaveBeenCalledはモック関数が呼ばれたことを確認できます。

function drinkAll(callback, flavour) {
  if (flavour !== 'octopus') {
    callback(flavour);
  }
}

describe('drinkAll', () => {
  test('drinks something lemon-flavoured', () => {
    const drink = jest.fn();
    drinkAll(drink, 'lemon');
    expect(drink).toHaveBeenCalled();
  });

  test('does not drink something octopus-flavoured', () => {
    const drink = jest.fn();
    drinkAll(drink, 'octopus');
    expect(drink).not.toHaveBeenCalled();
  });
});

toHaveBeenCalledTimes(nimber)

toHaveBeenCalledTimesはモック関数が期待した回数だけ呼ばれたことを確認できます。

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenCalledTimes(2);
});

toHaveBeenCalledWith(arg1, arg2, …)

toHaveBeenCalledWithはモック関数が特定の引数を与えられて呼び出されたことを確認できます。

test('registration applies correctly to orange La Croix', () => {
  const beverage = new LaCroix('orange');
  register(beverage);
  const f = jest.fn();
  applyToAll(f);
  expect(f).toHaveBeenCalledWith(beverage);
});

toHaveBeenLastCalledWith(arg1, arg2, …)

toHaveBeenLastCalledWithはモック関数の最後の呼び出しでどんな引数が渡されたかを確認できます。

test('applying to all flavors does mango last', () => {
  const drink = jest.fn();
  applyToAllFlavors(drink);
  expect(drink).toHaveBeenLastCalledWith('mango');
});

toHaveBeenNthCalledWith(nthCall, arg1, arg2, …)

toHaveBeenNthCalledWithはn番目に呼び出された引数を確認できます。

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenNthCalledWith(1, 'lemon');
  expect(drink).toHaveBeenNthCalledWith(2, 'octopus');
});

n番目の引数は、1から始まる正の整数である必要があります。

toHaveReturned()

toHaveReturnedはモック関数が正常に返されたこと (エラーをスローしなかったこと) を確認できます。

test('drinks returns', () => {
  const drink = jest.fn(() => true);

  drink();

  expect(drink).toHaveReturned();
});

toHaveReturnedTimes(number)

toHaveReturnedTimesはモック関数が期待した回数だけ正常に返されたこと (エラーをスローしなかったこと)を確認できます。

test('drink returns twice', () => {
  const drink = jest.fn(() => true);

  drink();
  drink();

  expect(drink).toHaveReturnedTimes(2);
});

toHaveReturnedWith(value)

toHaveReturnedWithはモック関数が特定の値を返したことを確認できます。

test('drink returns La Croix', () => {
  const beverage = {name: 'La Croix'};
  const drink = jest.fn(beverage => beverage.name);

  drink(beverage);

  expect(drink).toHaveReturnedWith('La Croix');
});

toHaveLastReturnedWith(value)

toHaveLastReturnedWithはモック関数が最後に返した値を確認できます。

モック関数の最後の呼び出しでエラーがスローされた場合、期待される戻り値として指定した値に関係なく、テストは失敗になります。

test('drink returns La Croix (Orange) last', () => {
  const beverage1 = {name: 'La Croix (Lemon)'};
  const beverage2 = {name: 'La Croix (Orange)'};
  const drink = jest.fn(beverage => beverage.name);

  drink(beverage1);
  drink(beverage2);

  expect(drink).toHaveLastReturnedWith('La Croix (Orange)');
});

toHaveNthReturnedWith(nthCall, value)

toHaveNthReturnedWithはn回目の呼び出しでモック関数が返した値を確認できます。

モック関数のn回目の呼び出しでエラーがスローされた場合、期待される戻り値として指定した値に関係なく、テストは失敗になります。

test('drink returns expected nth calls', () => {
  const beverage1 = {name: 'La Croix (Lemon)'};
  const beverage2 = {name: 'La Croix (Orange)'};
  const drink = jest.fn(beverage => beverage.name);

  drink(beverage1);
  drink(beverage2);

  expect(drink).toHaveNthReturnedWith(1, 'La Croix (Lemon)');
  expect(drink).toHaveNthReturnedWith(2, 'La Croix (Orange)');
});

n番目の引数は、1から始まる正の整数である必要があります。

toHaveLength(number)

toHaveLengthはアサートするオブジェクトにlengthプロパティがあり、特定の値が設定されていることを確認します。

配列や文字列のサイズを確認するのに使用します。

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

toHaveProperty(keyPath, value?)

toHavePropertyはアサートするオブジェクトに指定したキーが存在するかどうか、またはそのキーの値を確認できます。

オブジェクトのより深いプロパティにアクセスするためにはドット表記でアクセスできます。

上記以外でも、配列でより深いプロパティにアクセスすることもできます。

// Object containing house features to be tested
const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
    'nice.oven': true,
  },
  livingroom: {
    amenities: [
      {
        couch: [
          ['large', {dimensions: [20, 20]}],
          ['small', {dimensions: [10, 10]}],
        ],
      },
    ],
  },
  'ceiling.height': 2,
};

test('this house has my desired features', () => {
  // Example Referencing
  expect(houseForSale).toHaveProperty('bath');
  expect(houseForSale).toHaveProperty('bedrooms', 4);

  expect(houseForSale).not.toHaveProperty('pool');

  // Deep referencing using dot notation
  expect(houseForSale).toHaveProperty('kitchen.area', 20);
  expect(houseForSale).toHaveProperty('kitchen.amenities', [
    'oven',
    'stove',
    'washer',
  ]);

  expect(houseForSale).not.toHaveProperty('kitchen.open');

  // Deep referencing using an array containing the keyPath
  expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);
  expect(houseForSale).toHaveProperty(
    ['kitchen', 'amenities'],
    ['oven', 'stove', 'washer'],
  );
  expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');
  expect(houseForSale).toHaveProperty(
    'livingroom.amenities[0].couch[0][1].dimensions[0]',
    20,
  );
  expect(houseForSale).toHaveProperty(['kitchen', 'nice.oven']);
  expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);

  // Referencing keys with dot in the key itself
  expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
});

toBeCloseTo(number, numDigits?)

toBeCloseToは浮動小数点数がほぼ等しいかどうかを確認できます。

任意の引数であるnumDigitsは小数点の桁数を指定できます。(指定した桁数の精度でアサート)

test('adding works sanely with decimals', () => {
  expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});

toBeDefined()

toBeDefinedは変数が未定義でないことを確認できます。

何かしらの関数で値が返却されることを確認したい場合などに使用します。

test('there is a new flavor idea', () => {
  expect(fetchNewFlavorIdea()).toBeDefined();
});

toBeFalsy()

toBeFalsyは値がfalseであることを確認します。

JavaScriptでは以下はfalseと判定されます。

  • false
  • 0
  • null
  • undefined
  • NaN
test('The isError is false', () => {
  const isError = false;
  expect(isError).toBeFalsy();
});

toBeGreaterThan(number | bigint)

toBeGreaterThanは数値の比較ができます。

指定した数値は含みません。

test('ounces per can is more than 10', () => {
  expect(ouncesPerCan()).toBeGreaterThan(10);
});

toBeGreaterThanOrEqual(number | bigint)

toBeGreaterThanOrEqualは数値の比較ができます。

指定した数値は含みます。

test('ounces per can is at least 12', () => {
  expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
});

toBeLessThan(number | bigint)

toBeLessThanは数値の比較ができます。

指定した数値は含みません。

test('ounces per can is less than 20', () => {
  expect(ouncesPerCan()).toBeLessThan(20);
});

toBeLessThanOrEqual(number | bigint)

toBeLessThanOrEqualは数値の比較ができます。

指定した数値は含みます。

test('ounces per can is at most 12', () => {
  expect(ouncesPerCan()).toBeLessThanOrEqual(12);
});

toBeInstanceOf(Class)

toBeInstanceOfはオブジェクトがあるクラスのインスタンスであることを確認できます。

class A {}

expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws

toBeNull()

toBeNullは値がnullであることを確認できます。

function bloop() {
  return null;
}

test('bloop returns null', () => {
  expect(bloop()).toBeNull();
});

toBeTruthy()

toBeTruthyは値がtrueであることを確認します。

test('The isError is true', () => {
  const isError = true;
  expect(isError).toBeTruthy();
});

toBeUndefined()

toBeUndefinedは値がundefinedであることを確認できます。

test('the best drink for octopus flavor is undefined', () => {
  expect(bestDrinkForFlavor('octopus')).toBeUndefined();
});

toBeNaN()

toBeNaNは値がNaNであることを確認できます。

test('passes when value is NaN', () => {
  expect(NaN).toBeNaN();
  expect(1).not.toBeNaN();
});

toContain(item)

toContainはアイテムが配列内にあるかどうかを確認できます。

test('the flavor list contains lime', () => {
  expect(getAllFlavors()).toContain('lime');
});

toContainEqual(item)

toContainEqualは特定の構造と値を持つオブジェクトが配列に含まれていることを確認できます。

配列内のアイテムをアサートする際は、オブジェクトの同一性ではなく、すべてのフィールドの等価性を再帰的にチェックします。

describe('my beverage', () => {
  test('is delicious and not sour', () => {
    const myBeverage = {delicious: true, sour: false};
    expect(myBeverages()).toContainEqual(myBeverage);
  });
});

toEqual(value)

toEqualはオブジェクトのすべてのプロパティを再帰的に確認できます。

プリミティブ値を比較する際に使用します。

const can1 = {
  flavor: 'grapefruit',
  ounces: 12,
};
const can2 = {
  flavor: 'grapefruit',
  ounces: 12,
};

describe('the La Croix cans on my desk', () => {
  test('have all the same properties', () => {
    expect(can1).toEqual(can2);
  });
  test('are not the exact same can', () => {
    expect(can1).not.toBe(can2);
  });
});

toMatch(regexp | string)

toMatchは文字列が正規表現と一致することを確認できます。

describe('an essay on the best flavor', () => {
  test('mentions grapefruit', () => {
    expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
    expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit'));
  });
});

もしくは文字列でもアサートできます。

describe('grapefruits are healthy', () => {
  test('grapefruits are a fruit', () => {
    expect('grapefruits').toMatch('fruit');
  });
});

toMatchObject(object)

toMatchObjectはJavaScriptオブジェクトがオブジェクトのプロパティのサブセットと一致することを確認できます。

オブジェクトの配列を渡すこともでき、この場合は受け取った配列内の各オブジェクトが配列内の対応するオブジェクトと一致する場合にのみtrueとなります。

const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
  },
};
const desiredHouse = {
  bath: true,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    wallColor: expect.stringMatching(/white|yellow/),
  },
};

test('the house has my desired features', () => {
  expect(houseForSale).toMatchObject(desiredHouse);
});

配列を渡した場合です。

describe('toMatchObject applied to arrays', () => {
  test('the number of elements must match exactly', () => {
    expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
  });

  test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
    expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
      {foo: 'bar'},
      {baz: 1},
    ]);
  });
});

toStrictEqual(value)

toStrictEqualはオブジェクトの型と構造が同じであることを確認できます。

class LaCroix {
  constructor(flavor) {
    this.flavor = flavor;
  }
}

describe('the La Croix cans on my desk', () => {
  test('are not semantically the same', () => {
    expect(new LaCroix('lemon')).toEqual({flavor: 'lemon'});
    expect(new LaCroix('lemon')).not.toStrictEqual({flavor: 'lemon'});
  });
});

toThrow

toThrowは関数が呼び出されたときにスローされることを確認できます。

function drinkFlavor(flavor) {
  if (flavor == 'octopus') {
    throw new DisgustingFlavorError('yuck, octopus flavor');
  }
  // Do some other stuff
}

test('throws on octopus', () => {
  expect(() => {
    drinkFlavor('octopus');
  }).toThrow();
});

参考

まとめ

この記事ではJestのMatcher(Assert)の一覧をまとめました。

是非、いいねやコメントをお願いします。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする

目次