📁
til
  • TIL(Today I Learned)
  • javascript
    • value-number-string-boolean-null-undefined
    • primitive-reference
    • Hoisting
    • Prototypes in Javascript
    • this
    • prototype
    • 콜백함수 (Callback function)
    • 함수의 호출
    • 자료구조 new keyword
    • closure
    • Promise
    • event-loop
    • array-object
    • 객체
    • Arguments
    • higher order function
    • operators-function-control-flow
    • 객체 생성 패턴 3가지
    • Javascript scopes
    • Functional Programming
    • Design Patterns
    • 데이터 타입
    • Object 객체
    • 표준 내장 객체의 확장
    • 참조
    • 함수
    • 상속(Inheritance)
    • this - 'this'를 사용하는 해당 함수를 '어떻게' 실행하느냐에 따른 4가지 this 정의
    • 전역객체(Global object)
    • 객체 지향 프로그래밍
    • The 'new' keyword - Object Creation in JavaScript
  • javascript-api
    • Number
      • Number.MAX_VALUE
      • Number.isInteger
      • Number.NEGATIVE_INFINITY
      • Number.isNaN()
      • Number.POSITIVE_INFINITY
      • Number.parseFloat
      • Number.EPSILON
      • number.toExponential
      • Number.MAX_SAFE_INTEGER
      • Number1 - 자연수, 정수, 10진수, 2진수, 부동소수점, 실수
      • Number.isSafeInteger()
      • Number.MIN_VALUE
      • Number.parseInt
      • Number.NaN
      • Number.isFinite()
      • Number.MIN_SAFE_INTEGER
      • toFixed
    • string.split
    • String.fromCodePoint
    • string.trimEnd
    • string.padStart
    • string.@@iterator
    • String.fromCharCode
    • string.toUpperCase
    • string.codePointAt
    • string.toLowerCase()
    • string.toString
    • string.includes
    • string.replace()
    • string.charAt
    • String.lastIndexOf
    • string.slice
    • string.search
    • string.padEnd
    • string.substring
    • string.length
    • string.trim
    • string.localeCompare
    • String.indexOf
    • string.endsWith
    • string.valueOf
    • String.raw
    • string.matchAll()
    • string.repeat
    • string.match
    • String.prototype
    • string.startsWith
    • string.charCodeAt
    • string.trimStart
    • string.concat
    • string.toLocaleUpperCase()
    • string.toLocaleLowerCase
    • String
  • learn-node
    • debugger
    • Tip
  • schema-design
    • Database Schema Design
    • Database Schema Design
  • react
    • LifeCycle
    • redux
    • Context API
    • 함수형 컴포넌트와 클래스, 어떤 차이가 존재할까?
    • Hooks과 useEffect 사용해 보기
    • Route
    • async wait 사용하기
    • Hooks API Reference
    • context
    • npm uninstall 하는법
    • test 만들기
  • tip
    • 클린코드
    • BxSlider로 텍스트 흐르는 효과 만들기
  • javascript30
    • Event Capture, Propagation, Bubbling and Once
    • Object and Arrays - Reference VS Copy
  • typescript
    • 우아한 타입스크립트 2부
    • The Basic Cheatsheet
    • TypeScript
    • Type Guards and Differnetiating Types
    • 우아한 타입스크립트
    • Generics
  • git-from-the-hell
    • git
    • init-status-add-commit-log-stage-repository
    • log-diff
    • 머지 후 branch 삭제하기
    • 지옥에서 온 Git
    • reset-revert
    • develop branch 를 pull 하고 싶을때
  • conference-and-seminar
    • 모던 프론트엔드 개발환경의 이해
  • fire-base
    • Firebase .gitignore
  • vanillacoding
    • Data Structures
    • Sorting Algorithms - part 1
    • Promise
    • class
    • 04.quiz
    • 07.event-loop
    • Design Patterns
    • OOP (Object Oriented Programming)
  • etc
    • 알고리즘 코드리뷰
    • 스스로 공부하는 법
    • 바닐라코딩 수강 후기
    • async 과제 후기 - 비동기, 동기, 클로저, 배열과 객체
    • 유용한 사이트
  • algorithm
    • The Supermarket Queue
    • Find the odd int
    • The Office III - Broken Photocopier
    • Directions Reduction
    • The Office II - Boredom Score
    • Divisible Sum Pairs
    • Codewars 이용자 솔루션 모음
    • Shortest Word
    • find key
    • Two Sum
    • Simple Pig Latin
  • Book
    • the essence of object-orientation
      • 타입과 추상화
      • 객체 지도
      • 이상한 나라의 객체
      • 추상화 기법
      • 05. 책임과 메시지
      • 07.함께 모으기
      • 04. 역할, 책임, 협력
      • 협력하는 객체들의 공동체
  • ecma-script2015
    • Object Literal Upgrades
    • default-parameter-template-literals-arrow-functions
    • spread-operator-rest-param
    • let-const-rest-parameter-spread-operator-destructuring
  • http
    • 웹 브라우저에 URL을 입력했을 때 어떻게 웹 페이지가 보여질까?
  • jest
    • toThrow(error?)
  • data-structures
    • Data Structures
  • express
    • express generator
    • CORS
  • css-flexible-box-layout
    • flex 해버렸지 뭐야
  • git
    • Git
  • mongodb
    • MongoDB
  • markdown
    • use-markdown
  • cmder
    • cmd 명령어 모음
  • debug
    • trackClicksEx function error
  • npm
    • NPM TOKEN 설정하기
  • storybook
    • Storybook
  • sort
    • Sorting Algorithms - part 1
  • javascript-koans
    • Javascript Koans 오답노트
  • rxjs
    • Rx.js
  • dom-elements
    • HTML Element
  • redux-toolkit
    • Redux Toolkit
  • github-actions
    • GitHub Actions
  • redux-middleware
    • redux middleware
  • rest
    • rest
  • css-rendering
    • 코드 스피츠 - CSS Rendering 1회차 2/2
    • 코드 스피츠 - CSS Rendering 1회차 1/2
  • you-dont-know-js
    • 타입
  • server
    • # shutdown local server
  • semantic-versioning
    • Semantic Versioning 2.0.0
Powered by GitBook
On this page
  • Utility 함수 test
  • Shallow Rendering
  • promise return하는지 확인하기
  • resolve확인하기

Was this helpful?

  1. react

test 만들기

Previousnpm uninstall 하는법Nexttip

Last updated 5 years ago

Was this helpful?

npm 설치

  • Jest 기본으로 설치 되어 있었음

  • npm install --save enzyme enzyme-adapter-react-16 react-test-renderer

    • Testing Components를 위해 필요하다.

  • npm install --save jest-enzyme

    • 코드를 더 간단하게 작성 할 수 있도록 도와준다.

  • yarn add enzyme-to-json

    • 스냅샷 테스팅을 도와준다.

파일 경로

  • src바로 아래에 tests 라는 폴더를 만들었다.

  • Utility 함수를 모아둔 helpers.test.js라는 파일이 있기 때문에 test 폴더안에 helpers.test.js라는 파일을 만듬

Utility 함수 test

helpers.test.js 파일

import { arrangeViewCount, arrangeTime, arrangeDay } from "../helpers";

it('arrange view count', () => {
  expect(arrangeViewCount()).toEqual(0);
  expect(arrangeViewCount(0)).toEqual(0);
  expect(arrangeViewCount(5)).toEqual('5');
  expect(arrangeViewCount(50000)).toEqual('5만');
  expect(arrangeViewCount(500000000)).toEqual('5억');
});

it('arrange time', () => {
  expect(arrangeTime()).toEqual(0);
  expect(arrangeTime(0)).toEqual(0);
  expect(arrangeTime('5')).toEqual('5');
  expect(arrangeTime('5h3m')).toEqual('5:3');
  expect(arrangeTime('5h3m1s')).toEqual('5:3:1');
});

it('arrange time', () => {
  expect(arrangeTime()).toEqual(0);
  expect(arrangeTime(0)).toEqual(0);
  expect(arrangeTime('5')).toEqual('5');
  expect(arrangeTime('5h3m')).toEqual('5:3');
  expect(arrangeTime('5h3m1s')).toEqual('5:3:1');
});

it('arrange day', () => {
  expect(arrangeDay()).toEqual('');
  expect(arrangeDay('2018-03-02T20:53:41Z')).toEqual('2018-03-02');
});

npm test로 실행 할 수 있다.

Shallow Rendering

참조 url

스냅샷 테스팅

렌더링된 결과가 이전과 동일한지 확인해주는 것이다. props 값을 변경하여 변경한 내용을 업데이트 하고 싶다면 터미널에서 u를 눌러준다.'ㅁ'/

promise return하는지 확인하기

CRA로 프로젝트를 시작하면, jest가 따로 있다.

toBeInstanceOf(class)

expect(getTitle()).toBeInstanceOf(Promise);

resolve확인하기

toEqual - deep equality ===

toBe - ==

test에는 done 이라는 인자가 항상 넘어온다.

test('', (done) => {

});

비동기 테스트할때 done을 사용한다.

test('should resolve to new title asynchronously', (done) => {
  jest.setTimeout(6000); // 기본 시간을 바꾼다.

  getTitle().then(title => {
    expect(title).toBe('new title');
    done(); // 비동기를 기다려준다.
  });
});

once

export function once(fn) {
  var returnValue;
  var called = false;

  return function () {
    if(!called) { // 함수를 한번만 실행하기 위한 조건문.
      called = true;
      returnValue = fn.apply(this, arguments);
    }
    return returnValue;
  }
}

가짜함수 mock

The Jest Object -> Mock Functions -> jest.fn

const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled(); // 함수가 실행됐는지 확인
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;

테스트해보기

const mockFn = jest.fn();

const newFoo = once(mockFn);

test('first', () => {
  newFoo(1, 2);
  expect(mockFn).toHaveBeenCalled();
});


newFoo(1, 2);

.toHaveBeenCalledTimes(number) // 몇번 호출됐는지 알 수 있다.

.toHaveBeenCalledWith(arg1, arg2) arg1~ 2가 들어가서 호출 됐는지 확인한다.

toHaveBeenCalledWith

인자까지 체크해 준다.

const mockFn = jest.fn();

const newFoo = once(mockFn);

test('first', () => {
  newFoo(1, 2);
  expect(mockFn).toHaveBeenCalledWith(1, 2);
});


newFoo(1, 2);

호출하는 내용을 추가한다.

const mockFn = jest.fn();

const newFoo = once(mockFn);

test('second', () => {
  newFoo(1, 2);
  expect(mockFn).toHaveBeenCalledWith(1, 2);
});


newFoo(1, 2);

beforeEach

describe에서 쓸 수 있다.

describe('', () => {
  beforeEach(() => {

  });

  describe('', () => {
    // 이때도 beforeEach가 실행된다.
  });
  test('', () => {}); 
})

test코드가 실행되기 전에 beforeEach안에 있는것들이 실행된다.

const는 스코프가 {} 한정이기 때문에 한단계 더 위에서 정의해준다.

describe('', () => {
  let mockFn;
  let newFoo;

  beforeEach(() => {
    mockFn = jest.fn();
    newFoo = once(mockFn);
  });

  describe('', () => {
    // 이때도 beforeEach가 실행된다.
  });
  test('', () => {}); 
})

toHaveBeenCalledTimes()

몇번 실행하는지 확인 할 수 있다.

react component test

exists

존재하는지 확인한다.

Create React App 참고 페이지
reactjs 페이지
enzyme
ceate-react-app
velopert님의 블로그 글