mercredi 14 septembre 2016

React Jest test component state is null

I created a carousel component. In this component, a user can click the next button and the carousel will scroll to the next position.

<div className='carousel-next-btn' onClick={this.nextImage}>

JS in my component:
getInitialState: function () {
  return {
    activeIndex: 0
  };
},
nextImage: function(){
    this.setState({ activeIndex: this.state.activeIndex + 1 })
} 

The test:

jest.dontMock('../Carousel.react.js');
jest.dontMock('react');
jest.dontMock('react-dom');

describe('Carousel', function () {
  var React = require('react');
  var ReactDOM = require('react-dom');
  var Carousel = require('../Carousel.react.js');
  var ReactTestUtils = require('react-addons-test-utils');

  var choices = ['images/image.png', 'images/image2.png'];
  var choice = 'images/image.png';
  var Component;

  beforeEach(function () {
      React = require('react');
      ReactDOM = require('react-dom');
      Carousel = require('../Carousel.react.js');
      ReactTestUtils = require('react-addons-test-utils');
      Component = ReactTestUtils.renderIntoDocument(<Carousel choices={choices} choice={choice}/>);
  });

  it('it always renders a div with a className of carousel', function () {
      var wrapperDiv = ReactTestUtils.scryRenderedDOMComponentsWithTag(Component, 'div');
      expect(wrapperDiv[0].classList).toContain('carousel');
    });

    it('should focus on the selected card when the carousel is focused on', function () {
      var nextBtn = ReactTestUtils.scryRenderedDOMComponentWithClass(Component, 'accarousel-next-btnive');
      ReactTestUtils.Simulate.click(nextBtn);
      jest.runAllTimers(); // timers are used as fallback animation in phantomjs
      var active = ReactTestUtils.scryRenderedDOMComponentsWithClass(Component, 'active');
      console.log( 'state', Component.state, 'props', Component.props );          
    });

  });

});

The output of the console.log is

state null props { choices: [ 'images/image.png', 'images/image2.png' ], choice: 'images/image.png' }

Why is state null and how can I get the activeIndex variable?

Aucun commentaire:

Enregistrer un commentaire