gpt4 book ai didi

reactjs - 浅层渲染使用 Refs 的 React/Enzyme 组件

转载 作者:行者123 更新时间:2023-12-03 14:14:43 26 4
gpt4 key购买 nike

我正在使用 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 是否被调用。

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

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。

谢谢。

最佳答案

我认为这是不可能的。

浅层渲染 docs没有 ref 属性的文档。但挂载渲染docs拥有它。

此外,您可以查看此 github issue .

在我看来,为了不使用挂载渲染,不要访问 classListnextElementSibling,而是设置相应的状态变量并根据该变量显示所需的 className。

关于reactjs - 浅层渲染使用 Refs 的 React/Enzyme 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38893986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com