Learn about different types of automated tests and how to apply them in React environment.
- End To End tests: Slow, complicated, brittle, complete
- Unit tests: Fast, simple, reliable, isolated
- Write a failing test
- Observe that it actually fails!
- Make sure that it fails with red
- Fix code so that the test passes
- GOTO 1
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!
- Jest - Delightful JavaScript Testing framework and toolset for testing
- Enzyme library for testing React components
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)
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
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
(You may think I am biased towards Eric Elliot - perhaps. But he does write well!)