vitest

vitest

expect.extend

์ปค์Šคํ…€ ๋งค์ฒ˜๋ฅผ ๋งŒ๋“ค๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉ๋จ

//expect-extend.ts
import { uuidRegExp } from '@__tests__/libs/reg-exp';
import { expect } from 'vitest';

expect.extend({
  toBeUuid(recived) {
    const { isNot } = this;
    
    const pass = uuidRegExp.test(received);
    const message = () => `expected ${received} to ${isNot ? ' not ' : ''} be uuid`;
    return {
      pass,
      message,
    }
  },
  
 toBeCloseDate(received, expected: Date) {
   const { isNot } = this;
   
   const min = 1;
   const range = min * 60 * 1000;
   
   const pass = (() => {
     if (!(received instanceof Date)) return false;
     const diff = received.getTime() - expected.getTime();
     const absDiff = Math.abs(diff);
     if (absDiff > range) return false;
     return true;
   })();
 }
})

test.each

์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ž…๋ ฅ๊ฐ’์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ™์€ ํ…Œ์ŠคํŠธ๋ฅผ ๋ฐ˜๋ณต ์‹คํ–‰ํ•  ๋•Œ ์“ฐ๋Š” ๊ธฐ๋Šฅ

import { faker } from '@faker-js/faker';
import { test, describe, expect } from 'vitest';
import { validateBody, validateTitle } from './content-validation';

describe('validateTitle', () => {
  test.each([
    {
      title: faker.string.sample(1),
      expected: false,
    },
    {
      title: faker.string.sample(81),
      expected: false,
    },
    {
      title: faker.string.sample(2),
      expected: true,
    },
  ])('($title.length) $title -> $expected', ({ title, expected }) => {
    const result = validateTitle(title);

    expect(result).toEqual(expected);
  });
});

describe('validateBody', () => {
  test.each([
    {
      body: faker.string.sample(20001),
      expected: false,
    },
    {
      body: faker.string.sample(20000),
      expected: true,
    },
  ])('($body.length) $body -> $expected', ({ body, expected }) => {
    const result = validateBody(body);

    expect(result).toEqual(expected);
  });
});

Last updated