- Mastering React Test:Driven Development
- Daniel Irvine
- 394字
- 2021-06-24 14:45:02
Rendering React from a test
In order to make this test pass, we'll have to write some code above the expectation that will call into our production code.
Since we're testing what happens when a React component is rendered, we'll need to call the ReactDOM.render function. This function takes a component (which in our case will be called Appointment), performs the React render magic, and replaces an existing DOM node with the newly rendered node tree. The DOM node it replaces is known as the React container.
Here's the method signature:
ReactDOM.render(component, container)
In order to call this in our test, we'll need to define both component and container. Let's piece the test together before we write it out in full. It will have this shape:
it('renders the customer first name', () => {
const component = ???
const container = ???
ReactDOM.render(component, container);
expect(document.body.textContent).toMatch('Ashley');
});
Since we're rendering Appointment, we know what we need to put for component. It's a JSX fragment that takes our customer as a prop:
const customer = { firstName: 'Ashley' };
const component = <Appointment customer={customer} />;
What about container? We can use the DOM to create a container element:
const container = document.createElement('div');
document.body.appendChild(container);
Now let's take a look at that test in full. Change your test in test/Appointments.test.js to match the following:
it('renders the customer first name', () => {
const customer = { firstName: 'Ashley' };
const component = <Appointment customer={customer} />;
const container = document.createElement('div');
document.body.appendChild(container);
ReactDOM.render(component, container);
expect(document.body.textContent).toMatch('Ashley');
});
As we're using both ReactDOM and JSX, we'll need to include the two standard React import at the top of our test file for this to work, as follows:
import React from 'react';
import ReactDOM from 'react-dom';
Go ahead and run the test. Within the output, you'll see the following:
ReferenceError: Appointment is not defined
This is subtly different from the test failure we saw previously. This is a run-time exception, not an expectation failure. Thankfully, though, the exception is telling us exactly what we need to do, just as a test expectation would. We need to define Appointment.
- Mastering Ext JS(Second Edition)
- Learn ECMAScript(Second Edition)
- UI圖標(biāo)創(chuàng)意設(shè)計(jì)
- Apache ZooKeeper Essentials
- SQL學(xué)習(xí)指南(第3版)
- 摩登創(chuàng)客:與智能手機(jī)和平板電腦共舞
- 劍指Offer(專項(xiàng)突破版):數(shù)據(jù)結(jié)構(gòu)與算法名企面試題精講
- 深入淺出Java虛擬機(jī):JVM原理與實(shí)戰(zhàn)
- 基于Java技術(shù)的Web應(yīng)用開發(fā)
- C語(yǔ)言從入門到精通(第4版)
- Python Network Programming Cookbook(Second Edition)
- 程序員修煉之道:通向務(wù)實(shí)的最高境界(第2版)
- OpenStack Orchestration
- Keras深度學(xué)習(xí)實(shí)戰(zhàn)
- C和C++游戲趣味編程