2019/10/06 TIL

HANJIN·2019년 10월 6일
0

TIL

목록 보기
13/14
post-thumbnail

check key in object with Jest

const obj = {a:1, b:2};
test('object "obj" has key "a"', () => {
  expect(obj).toHaveProperty('a'); // pass
  expect(obj).not.toHaveProperty('b'); // doesn't pass
}

check value's structure in object with Jest

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/), 
    // can use regexp for expect structure of string 
  },
};

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

another Test(also can apply to array)

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},
    ]);
  });
});
profile
소프트웨어 엔지니어.

0개의 댓글