JSX and Testing

COURSE 6 – ADVANCED REACT QUIZ ANSWERS

Week 3: JSX and testing

Meta Front-End Developer Professional Certificate

Complete Coursera Answers & Study Guide

Click to Enroll in Coursera Meta Front-End Professional Certificate

JSX and testing INTRODUCTION

Once you have achieved a strong understanding of SX, Coursera’s Meta Front-End Developer Professional Certificate will help you to apply your knowledge in real-world applications. This certificate is designed to teach advanced SX patterns and techniques, such as higher-order components and render props that encapsulate common behavior.

Additionally, this course provides guidance on effective strategies for testing and debugging SX applications. By completing the certificate, students will be equipped with the skills necessary to build reliable SX applications that adhere to industry standards.

This certification is endorsed by top employers and will provide an opportunity to demonstrate proficiency in SX development, giving graduates of the program a unique edge in the job market.

Learning Objectives

  • Define the types of children within JSX
  • Use JSX to apply React component composition with children.
  • Describe the process and purpose of creating higher-order components.
  • Describe the process and purpose of creating render props.
  • Write a test for a React application using Jest and React Testing Library.

SELF-REVIEW: BUILD A RADIO GROUP COMPONENT

1. In the RadioGroup component, when cloning each child element (RadioOption), what’s the condition that determines the value of the new checked prop that gets merged into the existing props of each RadioOption component? Recall that the RadioGroup component has three props – onChange, selected and children – and that each RadioOption component receives two props – value and children.

  • React.cloneElement(child, {  onChange,   checked: child.checked === true, });
  • React.cloneElement(child, {  onChange,  checked: child.props.selected, });
  • React.cloneElement(child, {  onChange,  checked: child.props.value === selected,}); (CORRECT)

Correct: That’s correct, the condition checks if the particular value prop from that radio option matches the selected value. If so, the checked prop will be true, which only can happen for one radio button at a time.

2. Inside the RadioOption component, what should be the value of the onChange prop from the radio input element? Recall that the RadioOption component receives four props – value, checked, onChange and children.

  • <input type="radio" onChange={e => onChange(e.target.value)} /> (CORRECT)
  • <input type="radio" onChange={props.onChange} /> 
  • <input type="radio" onChange={() => onChange(props.value)} />

Correct: That’s correct, that is the proper implementation to trigger a change in the current selection.

3. What are the arguments that the React.Children.map function receives?

  • The first argument is the children prop, and the second argument is a transformation function that returns a new React element. (CORRECT)
  • The first argument is the children prop, and there is no second argument. 
  • The first argument is the children prop, and the second argument is a predicate function that returns a boolean.

Correct: That’s correct, those are the two arguments the function receives.

KNOWLEDGE CHECK: JSX

1. Let’s suppose you have the below JSX that gets returned from a component, what would be the equivalent object representation (Element) that React will create internally?

  •  <button className='button-primary'>
        <div>
            Submit
        </div>
     </button>
    {
        type: "button",
        props: {
            className: "button-primary",
            children: {
                type: "div",
                props: {
                    children: "Submit",
                }
            },
        },
    } (CORRECT)
  • {
        type: "button",
        props: {
            className: "button-primary",
            children: {
                type: "div",
                children: "Submit"
            },
        },
    }
  •  {
        type: Button,
        props: {
            className: "button-primary",
            children: "div",
        },
    }

Correct: That’s correct, the children key also should point to an element, so it has to have two keys: type and props.

2. What is the concept of component specialization?

  • A component that doesn’t know its children ahead of time and acts as a generic box. 
  • A component that is designed to fulfill one specific purpose and nothing else. 
  • A component defined as a special case of another more generic component. (CORRECT)

Correct: That’s correct. For example, a SubmitButton component is a more specialized version of a Button component.

3. You would like to clone a React element by using the React.cloneElement API, where the particular element has the below structure:

const buttonElement = {
  type: SubmitButton,
  props: {
    color: "green",
    children: "Submit!",
  },
};

What would be the value of the variable output when using the API with the following parameters?

const output = React.cloneElement(buttonElement, {disabled: true, color: “blue” });
  • {
      type: SubmitButton,
      props: {
        color: "blue",
        children: "Submit!",
        disabled: true,
      },
    }; (CORRECT)
  • {
      type: SubmitButton,
      props:
     {
        disabled: true,
        color: "blue",
      },
    };
  • {
      type: SubmitButton,
      props:
     {
        color: "green",
        children: "Submit!",
        disabled: true,
      },
    };

Correct: That’s correct, the color props gets overridden and a new prop called disabled with a value of true gets added.

4. Imagine you are using the spread operator in the below component as follows:

const props = { title: "tiramisu", cal: 400 };
const element = <Component title="cake" {...props} cal={500} />;

What would be the value of element.props?

  • { title: "cake", cal: 400 } 
  • { title: "tiramisu", cal: 500 } (CORRECT)
  • { title: "tiramisu", cal: 400 } 
  • { title: "cake", cal: 500 } 

Correct: That’s correct, that’s the final value.

5. Amongst the below expressions, select all that will not render anything on the screen when being used in JSX.

  • <div>{false}</div> (CORRECT)
  • <div>{undefined}</div> (CORRECT)
  • <div>{(() => true)()}</div> (CORRECT)
  • <div>{null}</div> (CORRECT)

Correct: That’s correct, the false value will not render anything.

Correct: That’s correct, the undefined value will not render anything

Correct: That’s correct, the function gets invoked instantly in place and returns a value of true, which will not render anything.

Correct: That’s correct, the null value will not render anything.

SELF-REVIEW: IMPLEMENTING SCROLLER POSITION WITH RENDER PROPS

1. Considering the MousePosition component receives a prop called render, which is a function, what are valid options of JSX returned from the component?

  • return render(<div>{mousePosition}</div>); 
  • return render({ mousePosition }); (CORRECT)
  • return (
      <div>
        render({mousePosition})
      </div>); 

Correct: That’s correct, this component should not return any tags/elements and just call the render function with the mousePosition as argument.

2. The PointMouseLogger component returns the below JSX.

<p> ({mousePosition.x}, {mousePosition.y})</p>

After incorporating the MousePosition component as part of the JSX returned by PointMouseLogger, what should be the new JSX that PointMouseLogger returns?

return(
  <MousePosition
    render={({ mousePosition }) => (
      <p>
        ({mousePosition.x}, {mousePosition.y})
      </p>
    )}
  />
); (CORRECT)
return(
  <MousePosition>
    {({ mousePosition }) => (
      <p>
        ({mousePosition.x}, {mousePosition.y})
      </p>
    )}
  </MousePosition>
);
return(
  <MousePosition>
    <p>
      ({mousePosition.x}, {mousePosition.y})
    </p>
  </MousePosition>
);

Correct: That’s correct, the render prop should now return the previous JSX from the component, with the mousePosition being injected as an argument.

3. The App component initially presents the below output structure

function App() {
  return(
    <div className="App">
      <header className="Header">Little Lemon Restaurant 🍕</header>
      <PanelMouseLogger />
      <PointMouseLogger />
    </div>
  );
}

After adding the MousePosition component into the mix, would you still have to perform any changes to the App component?

  • No (CORRECT)
  • Yes

Correct: That’s correct, the App component shouldn’t be altered at all. Only PanelMouseLogger and PointMouseLogger components require changes to read the mousePosition data using the render prop from MousePosition component.

KNOWLEDGE CHECK: REUSING BEHAVIOR

1. When dealing with cross-cutting data in your React applications, what are some of the problems of using a custom hook to encapsulate that logic? Select all that apply.

  • There are no problems at all with hooks, being the best suited tool for the job.
  • That it turns a stateless component into a stateful one. (CORRECT)
  • The fact that you would have to alter the implementation of each component that needs that specific data. (CORRECT)

Correct: That’s correct, the addition of a custom hook that deals with specific data introduces state into the component.

Correct: That’s correct, you would have to add the custom hook to each particular component that needs that data.

2. Here, you can find the APIs of some higher-order components that have been already implemented. Amongst all the options, which ones present an invalid signature that doesn’t follow the convention? Select all that apply.

  • withSubscription(Component, options) 
  • withSubscription(() => getData())(Component) 
  • withSubscription(() => getData(), Component) (CORRECT)

Correct: That’s correct, the component should come as the first argument and any additional parameters should go afterwards.

3. What are some of the best practices to follow when implementing the higher-order component pattern? Select all that apply.

  • Mutate the original component 
  • Always use HOCs and create your enhanced components inside other components.
  • Maximize composability. (CORRECT)
  • Passed unrelated props through to the Wrapped Component. (CORRECT)

Correct: That’s correct, using proper API definitions allow you to combine different HOCs in a composable manner.

Correct: That’s correct, you should pass all the other props through to the wrapped component.

4. What are some of the differences between higher-order components and render props? Select all that apply.

  • Higher-order components modify the original implementation of the component, whereas the Render Props pattern doesn’t.
  • Render props provide the new data as a function parameter, whereas components wrapped with an HOC get the new data as a new prop. (CORRECT)
  • They inject the new props in the component to be enhanced in a different way. (CORRECT)

Correct: That’s correct, render props do so dynamically inside the JSX and HOCs provide an extra prop.

Correct: That’s correct, render props dynamically inside the JSX and HOCs as an extra prop.

5. True or false. A component with a render prop as renderer can do anything a higher-order component can do.

  • False 
  • True (CORRECT)

Correct: That’s correct, they are just two different implementations for encapsulating cross-cutting concerns, but they serve the same purpose.

SELF-REVIEW: WRITING MORE TEST SCENARIOS

1. What’s the correct call to fire an onChange event on an input with react-testing-library’s fireEvent API?

  • fireEvent.change(input, { target: { value: 'myValue' } }); (CORRECT)
  • fireEvent.change(input, { value: 'myValue' });
  • fireEvent.onChange(input, { target: { value: 'myValue' } }); 

Correct: Correct, those are the proper arguments.

2. How would you fire a click event on a submit button with react-testing-library fireEvent API?

  • fireEvent.click(button); (CORRECT)
  • fireEvent.onClick(button);
  • fireEvent.onClick(button, { target: { value: 'submit' } });

Correct: Correct, those are the proper arguments.

3. When locating an element by using one of the screen querying methods from react-testing-library, such as screen.getByRole or screen.getByLabelText, what would be the return value of the call if the element is not found?

  • undefined 
  • An error will be thrown
  • null (CORRECT)

Correct: Correct, that’s the value returned if the element is not found.

KNOWLEDGE CHECK: AUTOMATED TESTING

1. Why is automated testing important? Select all that apply.

  • It offers a faster feedback cycle, bringing faster validation and helping the development team to detect problems or bugs early. (CORRECT)
  • It saves time to development teams. (CORRECT)
  • It reduces human error. (CORRECT)

Correct: That’s correct, without test automation feedback for newly developed features can take a while.

Correct: That’s correct, development teams spend less time manually validating newly developed features.

Correct: That’s correct, manual testing opens up the opportunity for humans to make mistakes.

2. What are some of the best practices when writing your automated tests? Select all that apply

  • Your tests need to be focused on the implementation details of your components.
  • They should resemble the way your software is used. (CORRECT)
  • They should be maintainable in the long run. (CORRECT)

Correct: That’s correct, the more your tests resemble the way your software is used, the more confidence they can give you.

Correct: That’s correct, in that way, changes in the implementation of the component, but not functionality, won’t break your tests and slow you and your team down.

3. Imagine you have a component that renders both an input tag and a label tag with the exact text Comments:. Inside your test, you have the below piece of code:

const element = screen.getByLabelText(/Comments:/);

What would be the type of element returned by getByLabelText?

  • The input element (CORRECT)
  • The label element
  • The document object

Correct: That’s correct, the query looks for the label tag first, but it returns the input associated with it.

4. In a particular test that’s been written for a form component, you encounter the below two lines of code. What kind of data would the handleSubmit variable represent?

const handleSubmit = jest.fn();
render(<FeedbackForm onSubmit={handleSubmit} />);
  • A copy of the real function that’s used in the parent component that renders the FeedbackForm. 
  • A specific function jest provides to handle form submissions 
  • A mock function to track how is called by external code and thus explore the arguments passed in. (CORRECT)

Correct: That’s correct, handleSubmit is a special function called “a mock” that the jest library provides to track how it is called by external code.

5. What are some of the benefits of Continuous Integration (CI)? Select all that apply.

  • Faster manual integrations.
  • Deliver working software more often. (CORRECT)
  • Improved developer productivity. (CORRECT)
  • Find bugs earlier and fix them faster. (CORRECT)

Correct: That’s correct, it provides a faster feedback look.

Correct: That’s correct, developers can focus on programming the features the business needs.

Correct: That’s correct, the CI can run a suit of automated tests and check for failures, so developers are notified promptly.

Coursera Meta Front-End Developer Professional Certificate Answers and Study Guide

Liking our content? Then don’t forget to ad us to your bookmarks so you can find us easily!

Weekly Breakdown | Meta Study Guides | Back to Top

MODULE QUIZ: JSX AND TESTING

1. What are some of the features of component containment? Select all that apply.

  • A special case of other components.
  • A component that uses the children prop to pass children elements directly as their content. (CORRECT)
  • A component that acts as a generic box. (CORRECT)
  • The fact that some components don’t know their children ahead of time. (CORRECT)

Correct: Correct, all the content of the generic box is provided via the children prop.

Correct: Correct, like a Dialog or Alert.

Correct: Correct, they leverage the children prop.

2. What are the props that all components have by default? Select all that apply.

  • render 
  • type 
  • children (CORRECT)

Correct: Correct, all components have an implicit children prop.

3. What is a React Element? Select all that apply.

  • A React Component that represents a simple DOM node, like a button.
  • A JavaScript object that represents the final HTML output. (CORRECT)
  • An intermediary representation that describes a component instance. (CORRECT)

Correct: Correct, they represent what the UI should look like.

Correct: Correct, JSX gets transformed into that intermediary representation that is a descriptive object.

4. Assuming you have the below component, what are all the features implemented from component composition with children?

function ConfirmationDialog() {
  return (
    <Dialog color="blue">
      <h1 className="Dialog-title">
        Thanks!
      </h1>
      <p className="Dialog-message">
        We’ll process your order in less than 24 hours.
      </p>
    </Dialog>
  );
}
  • Component specialization. 
  • Component containment. 
  • Component specialization and component containment. (CORRECT)

Correct: Correct, ConfirmationDialog is a special case of Dialog and the Dialog is an example of a generic box (containment) that uses children to lay out the content.

5. What are some of the use cases that the React.cloneElement API allows you to achieve? Select all that apply.

  • Extend the functionality of children components. (CORRECT)
  • Modify children’s properties. (CORRECT)
  • Add to children properties. (CORRECT)

Correct: That’s correct. The React.cloneElement API allows you to extend the functionality of children components.

Correct: That’s correct. The React.cloneElement API allows you to modify children’s properties.

Correct: That’s correct. The React.cloneElement API allows you to add to children’s properties.

6. Assuming you have the following Row component that uses React.Children.map to perform some dynamic transformation in each child element, in order to add some custom styles, what’s wrong about its implementation? Select all that apply.

const Row = ({ children, spacing }) => {
  const childStyle = {
    marginLeft: `${spacing}px`,
  };
 
  return(
    <div className="Row">
      {React.Children.map(children, (child, index) => {
        child.props.style = {
          ...child.props.style,
          ...(index > 0 ? childStyle : {}),
        };
        
        return child;
      })}
    </div>
  );
};
  • Each child is missing a key, causing potential problems if the list order changes. 
  • You can’t use the spread operator in the style prop. 
  • Each child is being mutated. (CORRECT)

Correct: Correct, props are being mutated and that is a React breaking rule. You should use React.cloneElement to create a copy of the elements first.

7. Assuming you have the following set of components, what would be logged into the console when clicking the Submit button that gets rendered on the screen?

clicking the Submit button that gets rendered on the screen?
const Button = ({ children, ...rest }) => (
  <button onClick={() => console.log("ButtonClick")} {...rest}>
    {children}
  </button>
);
 
const withClick = (Component) => {
  const handleClick = () => {
    console.log("WithClick");
  };
 
  return (props) => {
    return <Component onClick={handleClick} {...props} />;
  };
};
 
const MyButton = withClick(Button);
 
export default function App() {
  return <MyButton onClick={() => console.log("AppClick")}>Submit</MyButton>;
}
  • “ButtonClick” 
  • “AppClick” (CORRECT)
  • “WithClick”

Correct: Correct, due to the order of the spread operator in the different components, the original onClick prop passed to MyButton takes precedence.

8. Among the below options, what are valid solutions to encapsulate cross-cutting concerns? Select all that apply

  • Components that consume context.
  • Render props pattern. (CORRECT)
  • Custom hooks. (CORRECT)
  • Higher order components. (CORRECT)

Correct: Correct, that’s one possible abstraction.

Correct: Correct, that’s one possible abstraction.

Correct: Correct, that’s one possible abstraction.

9. What does the screen utility object from react-testing-library represent when performing queries against it?

  • The whole virtual DOM 
  • The whole page or root document (CORRECT)
  • Your laptop screen

Correct: That’s correct, the screen utility object from react-testing-library represents the root document when performing queries against it.

10. When writing tests with Jest and react-testing-library, what matcher would you have to use to assert that a button is disabled?

  • ToBeInTheDocument 
  • toHaveBeenCalled 
  • toHaveAttribute (CORRECT)

Correct: That’s correct, When writing tests with Jest and react-testing-library, you would use toHaveAttribute to assert that a button is disabled.

11. Which of the examples below are valid types for Elements? Select all that apply. 

  • ype: “<div />”   
  • type: “button”  (CORRECT)
  • type: DeleteButton Where DeleteButton is a React component. (CORRECT)
  • type: “div”  (CORRECT)

Correct: That’s correct. This is an example of how React specifies a ‘type’ attribute when performing a tree transformation with simple DOM nodes.  

Correct: That’s correct. React would identify a component named DeleteButton as a function and ask that component what element it renders to, with the given props.  

Correct: That’s correct. This is an example of how React specifies a type attribute when performing a tree transformation with simple DOM nodes.  

12. Which of the statements below clearly states the definitions of Containment and Specialization? Select all that apply.  

  • Containment refers to the fact that some components know all of their children ahead of time.  
  • Specialization defines components as being “unique” from all other components.  
  • Specialization defines components as being “special cases” of other components. (CORRECT)
  • Containment refers to the fact that some components don’t know their children ahead of time. (CORRECT)

Correct: That’s correct! Specialization defines components as being “special cases” ofother components. For example, the ConfirmationDialog is a special case of Dialog.  

Correct: That’s correct! Containment refers to the fact that some components don’t know their children ahead of time. And can also be described as generic boxes, like a Dialog or Alert. 

13. Which of the following operations does the React.cloneElementAPI enable a parent to perform? Select all that apply.  

  • Transform React props directly  
  • Extend the functionality of children components  (CORRECT)
  • Add to children properties (CORRECT)
  • Modify children properties  (CORRECT)

Correct: That’s correct! Props in React are immutable objects, so onceReact.cloneElement has created a copy of the element it can then extend the functionality of the children components.   

Correct: That’s correct! Props in React are immutable objects, so onceReact.cloneElement has created a copy of the element it can then add to the childrens properties in the copy.  

Correct: That’s correct! Props in React are immutable objects, so onceReact.cloneElement has created a copy of the element it can then modify the childrens properties in the copy. 

14. A simple welcome screen for Little Lemon restaurant has been built, where users are able to sign up or login, depending on whether they have an account or not. The App component renders two buttons and uses the Button component for the sign up and the LoginButton component for log in.  

  • Both buttons make use of the onClick handler, to show an alert about the intended action when they are pressed. 
  • The same alert message that has been provided for Sign up, is used on the LoginButton component, hence overriding the onClick handler that the LoginButton already defines internally. 
  • What would the message of the alert be when the Sign up button is clicked? 
  • Signing up  
  • Logging in (CORRECT)

Correct: That’s right! Even though the onClickprop in the LoginButtoncomponent is overridden, its implementation prevents that overriding from happening, due to the order of the spread operator.  

15. A higher order component (HOC), is an advanced pattern that emerges from React’s compositional nature. 

  • What are some of the benefits of using a HOC in your solution? 
  • It uses a custom hook to encapsulate logic, making each component that needs that data stateful.  
  • It enhances or extends the capabilities of the component provided.  (CORRECT)
  • You can define logic in a single place, share it across many components, and keep them unchanged and stateless.  (CORRECT)

Correct: That’s correct. A HOC transforms a component into another component. In other words, it enhances or extends the capabilities of the component provided.  

Correct: That’s correct. A HOC transforms a component into another component. In other words, it enhances or extends the capabilities of the component provided.  

16. When defining a HOC, such as withMousePosition, why is the with part of the HOC name a general convention recommended by React?  

  • It expresses the enhancing nature of the technique. (CORRECT)
  • It expresses that the initial state will be an object with two properties, x and y.  
  • It expresses that mouse tracking logic will be implemented in each component.

Correct: That’s correct! The with part of the HOC name is a general convention recommended by React, as it expresses the enhancing nature of the technique, like providing a component ‘with’ something else.  

17. What is the result of the return statement of the DataFetcher component? 

  • The component returns the result of calling the render function. (CORRECT)
  • The component returns the result of the useEffect function.
  • The component returns the result of calling the fetch function.
  • The component returns multiple props.

Correct: That’s correct! The DataFetcher component returns the result of calling the render function and has no other rendering business.

18. Which of the following statements are true about Jest and React Testing Library tool? Select all that apply.  

  • React Testing Library is a JavaScript test runner that lets you access anartificial DOM, which provides an approximation of how the browserworks.  
  • Jest is a set of utilities that let you test React components without relying on their implementation details.   
  • Jest is a JavaScript test runner that lets you access an artificial DOM,which provides an approximation of how the browser works.  (CORRECT)
  • React Testing Library is a set of utilities that let you test React components without relying on their implementation details. (CORRECT)

Correct: That’s correct! Jest is a JavaScript test runner that lets you access an artificial DOM called jsdom. While jsdom is only an approximation of how the browser works, it is often good enough for testing React components.  

Correct: That’s correct! React Testing Library is designed to fulfill all testing best practices out of the box, so that you are able to focus on the business logic your tests need to run assertions on.  

19. When writing a part of your test to locate the range input and fill it with a value, which functions do you need to use?   

  • onChange   
  • handleSubmit   
  • screen.getByLabelText  (CORRECT)
  • fireEvent.change() (CORRECT)

Correct: That’s correct. Screen.getByLabelText asks the root document to find a label tag whose text contains a specified text value and then return the input element associated with that label.  

Correct: That’s correct. To fill the input and update the state with a value, you can use the fireEvent.change() utility from React Testing Library.  

Interactive CSS CONCLUSION

Now that you understand JSX in depth, and how to encapsulate common behaviour via higher-order components and render props, it’s time to learn how to test and debug your application.

Join Coursera now for access to our course on testing React applications with Jest! This course will teach you everything you need to know about testing React apps, from simple unit tests to complex end-to-end tests. After taking this course, you’ll be able to confidently write tests for your own React applications. Enroll now and get started today!

Subscribe to our site

Get new content delivered directly to your inbox.

Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!