0

Below is the component Calculator.

import SubComponent from './SubComponent';
export default class Calculator extends React.Component {
  render() {
    const {
      result,
    } = this.state;

    return (
      <form>
        <input
          type="number"
          defaultValue={0}
          ref={(el) => this.elements.value1 = el}
        />
        <input
          type="number"
          defaultValue={0}
          ref={(el) => this.elements.value2 = el}
        />
        <button type="button" onClick={this.add} />
        <p className="result">{result}</p>
        <SubComponent name="sub component"></SubComponent>
      </form>
    );
  }


}

And below is the SubComponent.

import React from 'react';
import SubSubComponent from './SubSubComponent ';

const SubComponent = ({ name }) => (
  <div>
    {`${name}`}
    <SubSubComponent name="sub sub component"  />
  </div>
);

export default SubComponent;

And below is the subsubcomponent referenced by subcomponent.

import React from 'react';
import SubSubComponent from './SubSubComponent ';

const SubComponent = ({ name }) => (
  <div>
    {`${name}`}
    <SubSubComponent name="sub sub component"  />
  </div>
);

export default SubComponent;

When I tested the shallow and mount method provided by enzyme like below.

const calculator = shallow(
  <Calculator />
);
console.log(calculator.html());

const calculator2 = mount(
  <Calculator />
);
console.log(calculator2.html());

They both print below html.

<form><input type="number" value="0"><input type="number" value="0"><button type="button"></button>
  <p class="result"></p>
  <div>sub component<div>sub sub component</div>
  </div>
</form>

But the shallow render in the doc said 'Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components.'

So I thought the shallow does not render the child component. Could you please explain the differences between the two method? Thanks.

Thiago Murakami
  • 965
  • 7
  • 11
liam xu
  • 2,892
  • 10
  • 42
  • 65

1 Answers1

1

The html function returns the entire markup, including sub-components. It treats shallow and deep mounted components the same, fully rendering the tree.

See the docs here.

If you show the output of shallow a different way, it should show the shallow output. For example:

expect(calculator).toEqual(...);

or

expect(wrapper.find(SubComponent).length).toBe(1);

Shallow mounting (without use of html) renders a component <SubComponent /> as <SubComponent /> whereas deep mounting would render the contents of the sub-component. See this answer for a more detailed explanation of shallow vs deep mounting.

A Jar of Clay
  • 5,622
  • 6
  • 25
  • 39