Jestを使用したTDD練習-基本Matcher


Jestはmatcherを使用して、必要な値をテストします.
Common Matchers
toBetoBeは、値が完全に一致しているかどうかを確認します.
test('tow plus tow is four', () => {
  expect(2 + 2).toBe(4);
})
toBeを使用する場合に注意すべき点は、テスト対象である.toBeによる対象試験は、値の一致ではなく、両方の値が同じ場合(Object.is)に合格した.
test('object', () => {
  const data = { one: 1 };
  const result = data;
  
  expect(data).toBe(result); // pass
  expect(data).toBe({ one: 1 }); // fail
});
toEqual
オブジェクトまたは配列の値を比較して、一致するかどうかを決定します.
test('object assingment', () => {
  const data = { one: 1 };
  
  expect(data).toEqual({ one: 1 }); // pass
});
not
現在使用しているマッチングとは逆のマッチングを使用する場合は、notを使用します.
test('adding positive number is not zero', () => {
  for (let = 1; a < 10; a++) {
    for (let b = 1; b < 10; b++) {
      expect(a + b).not.toBe(0);
    }
  }
});
Truthiness
テストではundefined、null、falseの値を区別する必要がありますが、異なる処理をしたくない場合があります.Jestはそのためにmatcherを用意した
test('null', () => {
  const n = null;
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).not.toBeUndefined();
  expect(n).not.toBeTruthy();
  expect(n).toBeFalsy();
});

test('zero', () => {
  const z = 0;
  expect(z).not.toBeNull();
  expect(z).toBeDefined();
  expect(z).not.toBeUndefined();
  expect(z).not.toBeTruthy();
  expect(z).toBeFalsy();
});
Numbers
数値を比較する方法に関連するmatcherも存在する.
test('two plus two', () => {
  const value = 2 + 2;
  expect(value).toBeGreaterThan(3);
  expect(value).toBeGreaterThanOrEqual(3.5);
  expect(value).toBeLessThan(5);
  expect(value).toBeLessThanOrEqual(4.5);

  // 숫자 테스트에서는 toBe와 toEqual은 동일합니다.
  expect(value).toBe(4);
  expect(value).toEqual(4);
});
浮動小数点試験はtoBeであり、toBeCloseToではない.
test('adding floating point numbers', () => {
  const value = 0.1 + 0.2;
  
  expect(value).toBe(0.3); // fail
  expect(value).toBeCloseTo(0.3); // pass
});
String
文字列をテストするとき、マッチング器は通常のテストを行う準備ができています.
test('there is no I in team', () => {
  expect('team').not.toMatch(/I/);
});

test('but there is a "stop" in Christoph', () => {
  expect('Christoph').toMatch(/stop/);
});
文字列テストはまた、toBeおよびtoEqualを提供する.
Arrays and iterables
アレイまたはiterableで、いくつかの項目があるかどうかをテストできます.
const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'milk',
];

test('the shopping list has milk on it', () => {
  expect(shoppingList).toContain('milk');
  expect(new Set(shoppingList)).toContain('milk');
})
Exceptions
また、関数の呼び出し中にエラーが発生した場合にテストすることもできます.toContainを使えばいいです.
function compileAndroidCode() {
  throw new Error('you are using the wrong JDK');
}

test('compiling android goes as expected', () => {
  expect(() => compileAndroidCode()).toThrow(); // 에러 발생 여부 확인
  expect(() => compileAndroidCode()).toThrow(Error); // 특정 에러 발생 여부 확인
  
  expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK'); // 에러 메시지 확인
  expect(() => compileAndroidCode()).toThrow(/JDK/) // 에러 메시지를 정규식으로 확인
})
Object
toMatchObject
オブジェクトに特定の属性または属性の値があるかどうかをテストしたい場合があります.
const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove'],
    area: 20
  }
};
const desiredHouse = {
  bath: true,
  kitchen: {
    amenities: ['oven', 'stove'],
    area: expect.any(Number),
  },
}

test('the house has my desired features', () => {
  expect(houseForSale).toMatchObject(desiredHouse);
});
上記のコードに示すように、オブジェクトのいくつかのプロパティをテストできます.値ではなくtoThrowで属性タイプをテストすることもできます.
配列をテストするときは、すべての要素を持つ必要があります.配列の一部の要素をテストする場合は、expect.any(classType)を使用します.
test('arrayContaining', () => {
  expect(['oven', 'stove']).toMatchObject(['oven', 'stove']); // pass
  expect(['oven', 'stove']).toMatchObject(['oven']); // fail
  expect(['oven', 'stove']).toMatchObject(expect.arrayContaining(['oven'])); // pass
});
objectContainingexpect.arrayContainingは、objectContainingと同様の機能を有する.下図のように、テストに合格したことを確認します.
test('objectContaining', () => {
  const data = { position: { x: 0, y: 0 }, a: 1 };
  
  expect(data).toMatchObject({ a: 1 }); // pass
  expect(data).toEqual(expect.objectContaining({ a: 1 })); // pass
});
では2つの違いを見てみましょう値を比較すると、toMatchObjectは、サブオブジェクトの要素を含むいくつかの属性をテストします.ただし、toMatchObjectは、テストに合格するには、サブオブジェクトに完全な属性があることを求めます.
test('objectContaining', () => {
  const data = { position: { x: 0, y: 0 }, a: 1 };
  
  expect(data).toMatchObject({ position: { x: 0 } }); // pass
  expect(data).toEqual(expect.objectContaining({ position: { x: 0 } })); // fail
  expect(data).toEqual(expect.objectContaining({ position: expect.objectContaining({ x: 0 }) }))
});