Unit Testing

React with Jest and react-testing-library

Agenda

1. Jest

2. AAA

3. Unit testing React

4. Unit testing React by Example using TDD approach

5. Debugging unit tests

Jest

 Typical structures

  • describe()
  • it() or test()
  • beforeEach()
  • "expect()" assertions:
    • toEqual()
    • toBe()
    • toHaveBeenCalled()
    • toHaveBeenCalledWith()
  • "expect().not" matcher
  • jest.fn()
  • jest.mock()

Basic example

beforeEach()

  • helps keeping your unit tests DRY where it's possible by grouping common arrangements
  • works for each it() block which is inside of describe() it is defined in
  • each describe() block can have it's own beforeEach()

beforeEach() example

Mocking Modules

Automatic mock example

AAA

or Arrange, Act, Assert

  • put all of your unit test preparation/bootstrap code inside of Arrange section of unit test
  • perform action, result of which you want to test inside of Act section of unit test
  • check expected result of executed Action inside of Assert section of unit test

AAA example

Unit Testing React

Unit Testing React

using TDD

react-testing-library

  • ​rendering components
  • finding content inside rendered components
  • simulating user events
  • almost completely removes necessity of using act()

get vs find vs query

Now a bit of a live coding

Contacts 

oleksandr.hutsulyak@techmagic.co

kami_lviv

Useful Links

  • What if I don't have a time for all of those?
  • What to cover in a first place?
  • TDD or BDD (before or after?) or both?
  • TheOutplay - BDD+TDD based on QA test runs and acceptance criteria
  • Storybook as example of Visual component testing

Unit Testing React with Jest and react-testing-library

By Oleksandr Hutsulyak

Unit Testing React with Jest and react-testing-library

  • 680