This is the child article of ReactTestUtils - Tutorial. In this article, I will explain how to Check Class Name and Tag with examples.

Example

In this example state, properties defined. Input field is having myInput class
import React from 'react';
import SubRoot from './sub-root'

class Root extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      name: 'sample name'
    };
  }

  render() {
    return (
      <div>
        <h1>Hello World!!</h1>

        <p>
          Please input your name here:
          <input className="myInput"
            onChange={this.handleChange}
            value={this.state.name}
          />
        </p>
        <SubRoot/>
        <p>Hello, {this.state.name} </p>
      </div>
    );
  }

  handleChange(e) {
    var newName = e.target.value();

    this.setState({
      name: newName
    });
  }
}

export default Root;

Verify Class name

Get className property of the element.
it('check className', function () {
    var root = TestUtils.renderIntoDocument(<Root/>);
    var inputElm = TestUtils.findRenderedDOMComponentWithClass(root, 'myInput');
    expect(inputElm.className.match(/\bmyInput\b/)).toExist();
});

Verify Property Value 

Get props of the element
it('check properties', function () {
    var root = TestUtils.renderIntoDocument(<Root/>);
    var subRoot = TestUtils.findRenderedComponentWithType(root, SubRoot);
    expect(subRoot.props.myProp).toEqual("my prop value");
});

Verify State Value

Get state of the element
it('check state', function () {
    var root = TestUtils.renderIntoDocument(<Root/>);
    var rootElm = TestUtils.findRenderedComponentWithType(root, Root);
    expect(rootElm.state.name).toEqual("sample name");
});

0 comments:

Blogroll

Follow this blog by Email

Popular Posts