在酶中无法使用 instance().state 和 update() 更新状态

In enzyme cannot update state using instance().state and update()

我正在尝试使用酶测试我的 React 组件。该组件具有此渲染方法:

render() {
        let modal = null;
        let modalTitle = this.state.isEditing ? 'Edit Event' : 'Add Event';
        if (this.state.showModal) {
            modal = (<div className="event-modal">
                <Modal show={this.state.showModal} onHide={this.closeModal}>
                   ...
                 </Modal>
            </div>);
        }
        return (
            <div style={{height: '500px', width: '1000px'}}>
                <BigCalendar
                    events={this.props.events}
                    startAccessor='startDate'
                    endAccessor='endDate'
                    onSelectSlot={this.onDayClick}
                    selectable={true}
                    onSelectEvent={this.onEventClick}
                />
                {modal}
            </div>
        );
    }

在我的测试用例中,我想验证当 showModal = true 时模式是否显示,酶建议您使用 instance() 使您的组件处于正确的状态以进行详细测试,所以我尝试使用 instance() 和然后更新(),但它没有用。我最终运行的测试用例是使用 setState(),酶建议尽可能不要使用它。这是我的测试用例:

it('render should display modal if showModal is true', () => {
        const calendar = shallow(<CalendarPres events={[]}/>);
        //The commented out code does not work, but I'm not sure why
        //calendar.instance().state.showModal = true;
        //calendar.update();
        calendar.setState({showModal: true});
        expect(calendar.find('.event-modal').exists()).toBe(true);
    });

setState() 有效,但使用 instance() 然后 update() 无效。为什么 update() 不能正确地重新渲染我的组件?

酵素如你所说的推荐,但是这个就不太好了

 calendar.instance().state.showModal = true;

因为我们应该直接设置状态的唯一情况是在组件构造函数中。

在设置状态时,我们应该始终使用异步工作的setState()


来自here: 1 and 2


update() 方法仅在有内容需要更新时才有效。 update() 触发时状态似乎没有改变。