官术网_书友最值得收藏!

Extracting a test helper

The Git tag for this section is extracting-helpers. It contains solutions to the exercises from the previous chapter, so if you haven't completed the Exercises section yourself, then you should move to this tag now so that you're up to date.

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.

主站蜘蛛池模板: 织金县| 瑞安市| 阿拉善右旗| 灵璧县| 舟山市| 咸丰县| 南部县| 梧州市| 新郑市| 翁源县| 临湘市| 定陶县| 遂昌县| 阳东县| 安徽省| 台中市| 丰原市| 姚安县| 巢湖市| 金堂县| 温州市| 濮阳市| 景谷| 韶关市| 乌拉特后旗| 邯郸市| 原阳县| 綦江县| 云梦县| 油尖旺区| 普兰店市| 衡东县| 扎囊县| 新竹县| 侯马市| 调兵山市| 蒙城县| 凉城县| 扬中市| 高安市| 金寨县|