Jest Matchers


ハーモニーさんの講義による文章です.

toBe & toEqual


ソース
test('toBe는 obj가 같은 객체를 가리키고 있는지 확인한다', () => {

    const obj = {};

    expect(obj).toBe(obj); // true

});

test('객체의 내용이 같더라도 서로 다른 메모리에 있는 객체이기 때문에 toBe를 쓰면 false가 나온다.', () => {

    expect({ name: 'John' }).toBe({ name: 'John' }); // false

});

test('대신에 객체의 내용이 같은지를 확인하려면 toEqual을 써야 한다', () => {

    const obj = {};

    expect({ name: 'John' }).toEqual({ name: 'John' }); // true

});
そのため、テスト객체배열の場合、使用すべきtoEqual
// fn.js

const fn = {
  makeUser: (name, age) => ({ name, age }),
};

module.exports = fn;
// fn.test.js
const fn = require('./fn');

// 객체와 배열은 재귀적으로 돌면서 확인해야되기 때문에 toEqual을 사용해야 한다.
test('이름과 나이를 받아서 객체를 반환해줘', () => {
  expect(fn.makeUser('mike', 30)).toEqual({
    name: 'mike',
    age: 30
  })
})
TOEqualを使用してオブジェクトを確認し、テストに成功しました.

toEqual & toStrictEqual

toStrictEqual比toEqual엄격하다ToStrictEqualを使用することをお勧めします.
何らかの要因の発生は許されないundefined
const fn = {
  makeUser: (name, age) => ({ name, age, gender: undefined }),
};

module.exports = fn;
const fn = require('./fn');

test('이름과 나이를 받아서 객체를 반환해줘', () => {
  expect(fn.makeUser('mike', 30)).toEqual({
    name: 'mike',
    age: 30
  })
})

test('이름과 나이를 받아서 객체를 반환해줘', () => {
  expect(fn.makeUser('mike', 30)).toStrictEqual({
    name: 'mike',
    age: 30
  })
})
1回目のテストに成功し、ToStrictEqualを使用した2回目のテストに失敗しました.

toBeNull, toBeUndefined, toBeDefined

test('null은 null입니다.', () => {
  expect(null).toBeNull();
})

toBeTruthy, toBeFalsy

test('0은 false 입니다.', () => {
  expect(0).toBeFalsy();
})

数値関連

  • undefined:大
  • toBeGreaterThan:大きいか等しい
  • toBeGreaterThanOrEqual:小
  • toBeLessThan:以下
  • test('아이디는 10자 이상이여야 합니다.', () => {
      const id = "id_length_check"
      expect(id.length).toBeGreaterThanOrEqual(10);
    });
    

    toBeCloseTo

    test('0.1 + 0.2', () => { 
      expect(0.1 + 0.2).toBe(0.3); 
    });
    上のコードは通りそうですが、私たちが通常計算で使用しているtoBeLessThanOrEqualとは異なり、コンピュータは10진법で動作します.
    一部の小数は10進数から2進数に変換する過程で2진법記憶領域が限られた計算機は無限小数を有限小数に変換し、その過程で発生した무한 소수0.1+0.2!=0.3になりました
  • JAvaスクリプトの数は常に64ビットの浮動小数点です。

  • test('0.1 + 0.2 = 0.3', () => { 
      expect(0.1 + 0.2).toBeCloseTo(0.3); 
    });
    toBeCloseToは

    toMatch


    toMatchは、文字列を処理し、正規表現で文字列の位置を決定する関数です.
    test('Hello World에 e 라는 글자가 있나?', () => {
      expect('Hello World').toMatch(/e/);
    });
    
    test('Hello World에 h 라는 글자가 있나?', () => {
      expect('Hello World').toMatch(/h/i);
    });
  • 미세한 오차:Ignore caseを表し、対象文字列に対して大文字小文字が認識されない.
  • toContain


    要素の配置要素の位置を決定する関数です.
    test('유저 리스트에 Mike가 있나?', () => {
      const user = 'Mike';
      const userList = ['Mike', 'Jane', 'Kai'];
      expect(userList).toContain(user);
    });

    toThrow

    // fn.js
    
    const fn = {
      throwErr: () => {
        throw new Error('error가 발생합니다.');
      }
    };
    
    module.exports = fn;
    // fn.test.js
    
    const fn = require('./fn');
    
    // 에러가 발생하기 때문에, 성공 테스트
    test('이거 에러 나나요?', () => {
      expect(() => fn.throwErr()).toThrow();
    });
    
    // 에러가 발생하는 내용까지 비교해서 체크할 수 있다.
    test('이거 에러 나나요?', () => {
      expect(() => fn.throwErr()).toThrow('error가 발생합니다.');
    });