javascript - react 测试。如何测试 react 组件内部的功能

标签 javascript reactjs testing

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

 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)
})

我收到以下错误: 类型错误:无法读取未定义的属性“be” null._onTimeout (test/Components/Ad.unit.js:42:5)

最佳答案

这是一个使用 mocha、chai 和 enzyme 的示例:

组件:

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)
  })

})

关于javascript - react 测试。如何测试 react 组件内部的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41745415/

相关文章:

javascript - 在滚动上添加类名?

testing - 使用 PowerMockito 和 @BeforeClass 进行常规夹具设置

testing - 负载测试和性能测试有什么区别?

unit-testing - 我们应该在类级别还是函数级别创建任何类的对象

javascript - 在表中使用 jQuery 对日期和时间进行排序

javascript - 如何使用绝对位置定位元素?

reactjs - 如何在 Antd Input 上使用 React-Hook-Form?

javascript - 过滤数据并将其返回到 "permanent"数据旁边 - React

javascript - jqplot 仅在一个图表上显示荧光笔

javascript - iOS 的 UIWebView 使用的 JavaScript 引擎的名称是什么?