Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the width of a React component during test?

I'm trying to test a slider component.

This slider component can be variable in width. When you click on the "track" of the slider it should change the value and trigger an onChange callback. The value is a based on where you click on the track. If you click the halfway point when the min value is 100 and the max value is 200, then it should report a value of 150.

The problem I'm running into is that when I render the component using ReactTest.renderIntoDocument the component doesn't have any width, so it can't calculate a new value when you click on it.

Here is the component Slider.js

import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
import { noop } from 'lodash';
import style from './style.scss';

export default class Slider extends React.Component {
  render() {
    return (
      <div
        className='Slider'
        onClick={this.handleClick.bind(this)}
        {...this.props}
      >
        <div
          className='handle'
          style={{left: `${this.calculateLeft()}%`}}>
        </div>
        <div className='track'></div>
      </div>
    );
  }

  handleClick(e) {
    let node = ReactDOM.findDOMNode(this);
    let {clientX, clientY} = e;
    let {offsetLeft, offsetWidth, clientWidth} = node;
    let xPercent = (clientX - offsetLeft) / offsetWidth;
    console.log(offsetLeft, offsetWidth, clientWidth, xPercent);
    this.props.onChange(normalize(xPercent, this.props.min, this.props.max));
  }

  calculateLeft() {
    let numerator = this.props.value - this.props.min;
    let denominator = this.props.max - this.props.min;
    return numerator / denominator * 100;
  }
}

// Proptypes
// ----------------------------------------------------------------------------
Slider.propTypes = {
  // Callback for when the value changes.
  onChange: PropTypes.func,
  // The value for when the slider is at 0%
  min: PropTypes.number,
  // The value for when the slider is at 100%
  max: PropTypes.number,
  // The starting value
  value: validateValue,
}

Slider.defaultProps = {
  onChange: noop,
  min: 0,
  max: 100,
}

// Custom Validation
// ----------------------------------------------------------------------------
function validateValue(props, propName, componentName) {
  let value = props[propName];

  if (typeof(value) !== 'number') {
    return new Error(`value must be a number, got ${typeof(value)}`);
  }

  if (value > props.max || value < props.min) {
    return new Error(
      `value: ${value} must be between max: ${props.max}
      and min: ${props.min}`
    );
  }
}

// Helpers
// ---------------------------------------------------------------------------

function normalize(floatValue, min, max) {
  let range = max - min;
  let normalizedValue = floatValue * range + min;
  // cleverly restrict the value be between the min and max
  return [min, normalizedValue, max].sort()[1];
}

Stylesheet (style.scss):

.Slider {
  position: relative;
  display: block;
  width: 100px;

  .track {
    height: 4px;
    background: #666;
    border-radius: 2px;
  }

  .handle {
    width: 12px;
    height: 12px;
    background: #fff;
    border-radius: 10px;
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    transition: left 100ms linear;
  }
}

Here is my test:

import Slider from './Slider';
import React from 'react';
import {
  renderIntoDocument,
  findRenderedDOMComponentWithClass,
  findRenderedDOMComponentWithTag,
  Simulate
} from 'react-addons-test-utils';

describe('Slider', function() {

  describe('click', function() {
    it('triggers the onChange callback', function() {
      const onChange = sinon.spy();
      const component = renderIntoDocument(
        <Slider
          style={{width: 100, height: 40}}
          min={100}
          max={200}
          value={150}
          onChange={onChange}
        />
      );

      const track = findRenderedDOMComponentWithClass(component, 'track');

      Simulate.click(track, {clientY: 0, clientX: 10})
      expect(onChange).to.have.been.calledWith(110);
    });
  });
});

Test output

LOG LOG: 0, 0, 0, Infinity
click
  ✗ triggers the onChange callback
AssertionError: expected onChange to have been called with arguments 10
    onChange(200)

    at /components/Slider/test.js:99 < webpack:///src/components/Slider/test.js:55:6

Those log statements are from the handleClick() function in the component.

The width is zero so the denominator ends up being zero when calculating xPercent, which causes it to be Infinity. This causes it to just use the max value of 200.

TLDR

How do I make the component have width when rendering it during a test?

like image 958
Christian Schlensker Avatar asked Oct 25 '15 03:10

Christian Schlensker


People also ask

How do you set the width of a element in react?

To get the width of an Element in React: Set the ref prop on the element. In the useLayoutEffect hook, update the state variable for the width. Use the offsetWidth property to get the width of the element.

How do you set the height and width of a react?

The general way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.

How do I change the size of my react?

The different Switch sizes available are default and small. To reduce the size of default Switch to small, set the cssClass property to e-small .

How do you get the size of a component in react?

The size of a component is determined by the height and width of the container. It can be determined if we assign a ref to that component. The useRef function with ref attribute are used to get the current size of the component.


1 Answers

I've been fighting the same problem myself today - I'm building a component that will scale its text size based on the size of the element. Because renderIntoDocument places your component inside a detached DOM node, it isn't possible to calculate offsetWidth, clientWidth, etc.

Are you testing in a browser or node.js? (EDIT: I see you tagged the question PhantomJS so I'm guessing browser!) If you're in a browser you may be able to render the component into the DOM for real:

React.render(<Slider />, document.body);

If you're worried about test isolation, you can create an IFrame to render the component into, and clean that up afterwards:

beforeEach(function() {
    this.iframe = document.createElement('iframe');
    document.body.appendChild(this.iframe);
});

React.render(<Slider />, this.iframe.contentDocument.body);

afterEach(function() {
    document.body.removeChild(this.iframe);
});

Then call this.iframe.contentDocument.body.querySelectorAll('.track') to get the HTML Element and run your assertions against it (This is a plain HTML element, not a React component, so use the standard APIs to query it).

like image 126
Matt Holland Avatar answered Sep 29 '22 11:09

Matt Holland