【问题标题】:Testing component function in React with Enzyme and Jest在 React 中使用 Enzyme 和 Jest 测试组件功能
【发布时间】: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


    【解决方案1】:

    最直接的解决方案是检查状态是否相应改变:

    const component = shallow(<DataStructureForm />)
    const value = 'someValue';
    component.instance().handleChange('someName')({target: { value }});
    expect(component.state('someName')).toEqual(value)
    

    【讨论】:

    • 谢谢@Alex,这就是解决方案。问题是我没有怎么调用handleChange()函数。
    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 2019-07-26
    • 2020-04-08
    • 1970-01-01
    • 2020-07-17
    • 2017-02-12
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多