- Mastering React Test:Driven Development
- Daniel Irvine
- 278字
- 2021-06-24 14:45:07
Extracting a test helper
For more detailed instructions, see the To get the most out of this book section in the Preface.
In the first chapter, our test suites shared common code for constructing a DOM container element before each test. This element was used as the React root element. By doing this for each test, we avoided modifying global state. Let's extract that code so that we can re-use it across all of our test suites.
The shared code can be split into four parts:
- A common declaration of container in the describe block, accessible by all tests
- A beforeEach call to set container to a newly constructed container element
- A render function to insert DOM elements into the container
- Various expectations on the container to verify its content
At first glance, it might seem difficult to extract this logic since the container variable is manipulated in both a beforeEach block and each of our test functions. However, it's possible if we use a higher-order function that encapsulates its own state.
Create a new file test/domManipulators.js, and add the following content:
import ReactDOM from 'react-dom';
export const createContainer = () => {
const container = document.createElement('div');
return {
render: component => ReactDOM.render(component, container),
container
};
};
Calling domManipulators creates an empty DOM element, container, and then returns an object with two properties: render and container. We'll see how these can be used in the next section.
- Getting started with Google Guava
- CentOS 7 Linux Server Cookbook(Second Edition)
- R的極客理想:工具篇
- The HTML and CSS Workshop
- 單片機應用與調試項目教程(C語言版)
- Teaching with Google Classroom
- Learning Vaadin 7(Second Edition)
- Learning Node.js for .NET Developers
- Java Web應用開發給力起飛
- 單片機原理及應用技術
- ASP.NET 4.0 Web程序設計
- 人人都能開發RPA機器人:UiPath從入門到實戰
- 從零開始學UI:概念解析、實戰提高、突破規則
- Drupal Search Engine Optimization
- micro:bit軟件指南