React Testing Components
Introduction
Guiding principle for testing is
Testing Exactly what you are trying to test and nothing more
DOM Overview
Definition
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.
A Web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases. The Document Object Model (DOM) represents that same document so it can be manipulated. The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.
Document Element
This is one element in a DOM e.g. a div.
innerHTML vs outterHTML
InnerHTML is used for getting or setting a content of the selected whilst the outerHTML is used for getting or setting content with the selected tag. This is a referred to a lot by Web developers so here is a picture to remind people of the difference.
Testing Rendering
React Testing Library
React Testing Library is one of the most well known. They say,
- The more your tests resemble the way the software is used, the more confidence they can give you.
- Encourages rendering components to DOM nodes,
- Making asserts against DOM nodes
It's API tries to encourage tests to represent how the software is used by the user. For example these tests focus on how the user might access the screen, by label, by text
const r = render(<Message content="Some Stuff" isImportant={true} />);
r.getByLabelText('First Name')
r.getByText('2017-5-13')
r.getByTitle('introduction')
// Frown upon because as a user id are not visible but...
r.getByTestId('target')
Example Test
Here is a full example for testing the Date slide