反应测试。如何测试反应组件内部的功能

时间:2017-01-19 15:19:36

标签: javascript reactjs testing

在react组件中测试方法的正确方法是什么,在本例中为componentDidMount。我想在compoenent中测试setTimeOut函数。我应该使用存根吗?例如下面的代码:

 componentDidMount() {
        setTimeout(() => this.setState({ isOpen: true }), 1);
  }

如何测试被调用的setTimeout?

我试过以下内容并没有奏效。我错过了什么?

my imports:

import test from 'ava';
import React from 'react';
import { ad } from 'components/Ad/Ad';
import { shallow, mount } from 'enzyme';
import { stub } from 'sinon';
import { expect } from 'chai';
import  sinon from 'sinon';

let info;

test.beforeEach(() => {

  info = shallow(<ad {...props} />)
});

test('is active: true after mounting', done => {
  info.instance().componentDidMount()
  setTimeout(() => {
    info.state('active').should.be.true  <--line:42
    done()
  }, 0)
})

我收到以下错误: TypeError:无法读取属性&#39; be&#39;未定义的     null._onTimeout(test / Components / Ad.unit.js:42:5)

2 个答案:

答案 0 :(得分:1)

这是一个使用mocha,chai和酶的例子:

组件:

import React, {PropTypes as T} from 'react'
import classnames from 'classnames'

export default class FadeIn extends React.Component {
  constructor(...args) {
    super(...args)
    this.state = {active: false}
  }

  componentDidMount() {
    setTimeout(() => this.setState({active: true}), 0)
  }

  render() {
    const {active} = this.state
    return (
      <div className={classnames('fade-in', {active}, this.props.className)}>
        {this.props.children}
      </div>
    )
  }
}

FadeIn.propTypes = {
  className: T.string
}

FadeIn.displayName = 'FadeIn'

测试:

import React from 'react'
import {shallow} from 'enzyme'
import FadeIn from '../../src/components/FadeIn'

describe('FadeIn', () => {
  let component

  beforeEach(() => {
    component = shallow(<FadeIn/>)
  })

  it('is initially active: false', () => {
    component.state('active').should.be.false
    component.find('div.fade-in').prop('className').should.equal('fade-in')
  })

  it('is active: true after mounting', done => {
    component.instance().componentDidMount()
    setTimeout(() => {
      component.state('active').should.be.true
      component.find('div.fade-in').prop('className').should.equal('fade-in active')
      done()
    }, 0)
  })

})

答案 1 :(得分:0)

Mocha框架支持异步测试,并允许您在测试中使用setTimeout。然后在异步回调中进行断言。

describe('test component', function() {
    it('should have isOpen true', function(done) {
        // *** setup your component here *** 
        console.log('waiting 3 seconds...');
        setTimeout(function () {
            console.log('waiting over.')
            // ** assert component state.isOpen == true **
            done(); // callback to indicate that test is over
        }, 3000);
    });

How can I use setTimeout() functions within Mocha test cases?