【发布时间】:2018-11-12 22:57:19
【问题描述】:
我正在按照 Container/Presentational 模式测试一个组件。为了使我的覆盖率达到 100%,我需要测试我有一个 setState() 的 handleChange() 函数。问题是我只是在测试 Container 组件,并且该函数是在 Presentational 中调用的。
容器组件:
import React, { Component } from 'react'
import DataStructureFormView from './DataStructureFormView'
export default class DataStructureForm extends Component {
state = {}
handleChange = name => event => {
this.setState({
[name]: event.target.value
})
}
render() {
return (
<DataStructureFormView
handleChange={this.handleChange}
form={this.state}
/>
)
}
}
如您所见,DataStructureForm 是Container 组件,DataStructureFormView 是Presentational 组件。
测试文件:
import React from 'react'
import { shallow, mount } from 'enzyme'
describe('DataStructureForm', () => {
it('should call the handleChange() function and change the state', () => {
const component = mount(<DataStructureForm />)
const handleChange = jest.spyOn(component.instance(), 'handleChange')
component.instance().handleChange()
expect(handleChange).toBeCalled()
}
}
这是我做过的多种方法之一,但它没有测试 handleChange() 方法中的 setState()。
我还能做什么?
【问题讨论】:
标签: reactjs unit-testing jestjs enzyme