Unit test: A test written by a programmer for the purpose of ensuring that the production code does what the programmer expects it to do.
Other types of tests: integration test, end-to-end test, acceptance test, etc.
- Tests can improve API design π
- Tests can help document what something is supposed to do π
- Tests can improve developer confidence π
- jest: JavaScript test runner πββοΈ
- ts-jest: enables you to test Typescript projects with jest
- Don't worry, wizardry config sets this up for us
- jest-extended: provides additional jest matchers
- Ex.
.toBeTrue()
,.toIncludeAllMembers([members])
,.toSatisfy(predicate)
- Ex.
- enzyme: enables you to test the DOM representation of a component
- Use this to
shallow
render a component
- Use this to
- pupeteer: enables you to run tests in Chrome (headless by default)
- cypress: end-to-end testing framework
/**
* Inserts the provided separator after every item except the last one in the provided array of React nodes, returning a
* new array.
*/
function joinChildren(children: React.ReactNode[], renderSeparator: (index: number) => React.ReactNode) {
// intentionally empty
}
describe("joinChildren", () => {
it("handles an empty array", () => {
expect(joinChildren([], renderComma)).toEqual([]);
});
});
describe("joinChildren, fn)
=> used to logically group tests togetherit("handles an empty array", fn)
=> alias fortest
.fn
contains the expectations to testtoEqual
=> matcher
- Run fast π
- Easy to read π
- Test API rather than implementation
- Prevent regressions (catch bugs) π
In a wizard package run yarn test
View test results in console or in browser via open ./build/jest/test-results.html
In a wizard package run yarn test --inspect-jest-configuration
Example report-app's jest-config
- Statement: Has each statement in the program been executed?
- Branch: Has every branch of a control structure (ex.
if
/else
) been executed? - Function: Has each function in the program been called?
- Line: Has every line of the program been executed?
Under the hood jest uses istanbul for coverage reports π
Example report-app's test-coverage
There are many ways to test the same piece of code.
- Try to write tests before implementation code. A lot of the benefit of writing tests comes from writing test-able code
- Focus on readability
Topic for debate: describe.each table
exists but is it readable? π©ββοΈ
- Refactor existing tests (one idea
<QuillEditor>
) - Add tests to an untested component
- Reading
- First-Class Tests - by Robert C. Martin (Uncle Bob)
- Is Unit Testing worth the effort? - StackOverflow
- Code
- jest examples - Github
- jsdom - Github
- YouTube π₯πΏ