Skip to content

Latest commit

 

History

History

lesson-3

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

React Testing

The Goal

Learn about different types of automated tests and how to apply them in React environment.

Automated tests

Test pyramid by Martin Fowler

The test pyramid

  • End To End tests: Slow, complicated, brittle, complete
  • Unit tests: Fast, simple, reliable, isolated

How to write a good test

  1. Write a failing test
  2. Observe that it actually fails!
  3. Make sure that it fails with red
  4. Fix code so that the test passes
  5. GOTO 1

How to write a code that is easy to test

Pure functions for the win:

  • Given an input, always produces the same output
  • No side effects (including changing its arguments)

React Components are usually pure functions. Not a coincidence!

Tools that we will use

Tools that we will not use

E2E testing: Selenium, Webdrivers, Headless browsers, Robot Framework (because they take too much time to set up and learn)

Unit testing: Mocha, Chai, Expect, Istanbul, Sinon (because these are alternatives to Jest)

Server/API testing: Supertest (because we focus on frontend only, for now)

Hands on!

Excercise 1: Checkout lesson-3 folder and run the app! npm install, npm start

Excercise 2: Find your favourite bug

Excercise 3: Write a unit test and npm test

https://facebook.github.io/jest/docs/en/expect.html

Hint:

import { removeFromArray } from "./functions"

// test suite: organize your tests!
describe("functions.test.js: removeFromArray", () => {

    // single test
    it("should remove item from array", () => {
        const input = ... // prepare data
        const actual = ... // call the function here
        const expected = ... // what you want to see?
        expect(actual).toEqual(expected) // test!
    })
})

Excercise 4: Write a Component test using enzyme

http://airbnb.io/enzyme/docs/api/shallow.html

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#testing-components

import React from "react" // because we will use JSX
import Party from "./Party"
import { shallow } from "enzyme" // there are multiple kinds of rendering

describe("Party.js", () => {

    it("should display party name", () => {
        const party = { name: "MyParty", members: 100 } // some data that we pass to props
        const wrapper = shallow(<Party party={party} />)
        const text = wrapper.text()
        expect(text).toMatch("MyParty")
    })

})

Excercise 5: Write propTypes

Technically, this is not a test. But it will help you!

https://reactjs.org/docs/typechecking-with-proptypes.html

Reading and more links

(You may think I am biased towards Eric Elliot - perhaps. But he does write well!)