3

我有一个用 Enzyme 测试的 React 组件,例如,它看起来像这样:

import React, {Component} from 'react'

class Foo extends Component {
  constructor(props) {
    super(props)
    this.showContents = this.showContents.bind(this)
  }

  showContents() {
    this.button.classList.toggle("active")
    this.button.nextElementSibling.classList.toggle("show")
    this.props.onRequestShowContents()
  }

  render() {
    return (
      <div className="wrapper">
        <button ref={(ref) => this.button = ref} onClick={this.showContents}>Click to view contents</button>
        <div className="panel">
          {this.props.contents}
        </div>
      </div>
    )
  }
}

export default Foo

我正在使用 Mocha/Chai/Enzyme 编写一些单元测试,我想模拟按钮按下以检查我的 props func 是否被调用。

我的基本酶测试如下所示:

import React from 'react'
import { shallow } from 'enzyme'
import Foo from '../components/Foo'
import chai from 'chai'
import expect from 'expect'
var should = chai.should()

function setup() {
  const props = {
    onRequestShowContents: expect.createSpy(),
    contents: null
  }

  const wrapper = shallow(<Foo {...props} />)

  return {
    props,
    wrapper
  }
}

describe('components', () => {
  describe('Foo', () => {
    it('should request contents on button click', () => {
      const { props, wrapper } = setup()
      const button = wrapper.find('button')
      button.props().onClick() //this line causes the error
      props.onRequestShowContents.calls.length.should.equal(1)
    })
  })
})

有什么方法可以调整测试或我的组件代码以避免this.button在点击处理程序中访问时出错?我得到“TypeError:无法读取未定义的属性'classList'”。

我想把它作为一个浅渲染单元测试,不想用 mount 深度渲染这个组件,这需要使用类似浏览器的环境,比如 jsdom。

谢谢。

4

1 回答 1

3

我认为这是不可能的。

浅渲染文档没有ref属性文档。但是安装渲染文档有它。

此外,您可以查看此github 问题

在我看来,不使用挂载渲染,而不是访问classListand nextElementSibling,设置相应的状态变量并根据该变量显示所需的类名。

于 2016-08-11T11:44:41.830 回答