200408 TIL TDD - [Udemy] React Testing with Jest and Enzyme 1

» 1.5막, TIL (Today I Learned), 스터디, React.js

[Udemy] React Testing with Jest and Enzyme 1

섹션 1: Introduction to Jest, Enzyme and TDD

dir: demo

TDD = write test before we write the code

  1. write a shell version of code (기능 안하는 function)
  2. write the test (fail하는 test) - red part→ we want to see the test fail
  3. failing test 가지고 write code to pass → green part

Why TDD ?

  • 처음엔 effort가 많이 든다고 생각하지만 나중에 코드 수정 후에는 effort 없이 테스트를 다시 돌릴 수 있음
  • 결국엔 더 나은 코드를 짜게 됨 (better organized code, plan before coding, fewer bugs, great code coverage)
    • Code Coverage is a measurement of how many lines/blocks/arcs of your code are executed while the automated tests are running.

    코드 커버리지 80% 넘긴 썰

Jest

jest --watch : rerun the test if a change is made (since the last commit)

Enzyme (vs React DOM)

  • creates virtual DOM for testing
  • allows testing w/o a browser
  • shallow rendering = render components only one level deep (render parent, but use placeholders for children)
  • npm i –save-dev enzyme jest-enzyme enzyme-adapter-react-16
  • docs - https://enzymejs.github.io/enzyme/

    test(“renders w/o crashing”, () => { const wrapper = shallow(); console.log(wrapper.debug()) });

Types of tests

  • unit test = test one piece of code (usually one function)
  • integration test = how multiple units work together
  • acceptance / end-to-end(E2E) test = how a user would interact with app

Testing Goal

#1 ease maintenance tests not having to rewrite tests when you refactor

  • Testing Behavior ⭕️
    • set initial state - simulate button click - check displayed count to see that it was incremented by one
  • Testing Implementation 🚫
    • set initial state - simulate button click - check to see if particular function was called

—> testing implementation (function name) not behavior (display update)

#2 easy diagnosis of failing tests

  • difficult to diagnose test 🚫
    • test that after entire process - if it fails, can’t find what step was the problem / it needs further investigation
  • easier to diagnose ⭕️
    • after each user action - test expected internal state change or test that a particular function was called (→ testing implementation???) —> trade off && balance

No snapshots

because 1) no TDD 2) brittle 3) difficult to diagnose 4) no intent