酶:价值道具在模拟onChange事件时返回未定义

时间:2019-05-08 04:23:02

标签: reactjs jestjs enzyme

我正在尝试使用simulate函数来模拟onChange事件。我还将第二个参数传递给模拟事件onChange,因为该值是事件的一部分。但是以某种方式它给了我意外的结果,因为我传递给第二个参数的值返回undefined而不是new comment。对这个问题有想法吗?

CommentBox.js

import React from 'react';

class CommentBox extends React.Component {
    state = {
        comment: ''
    }

    handleChange = event => {
        this.setState({
            comment: event.value
        })
    }

    handleSubmit = event => {
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <h4>Add a comment</h4>
                <textarea onChange={this.handleChange} value={this.state.comment} />
                <div>
                    <button>Submit Comment</button>
                </div>
            </form>
        )
    }
}

export default CommentBox;

CommentBox.text.js

import React from 'react';
import { mount } from 'enzyme';
import CommentBox from 'components/CommentBox';

let wrapped;

beforeEach(() => {
    wrapped = mount(<CommentBox />);
})

afterEach(() => {
    wrapped.unmount();
})

it('has a textarea and a button', () => {
    expect(wrapped.find('textarea').length).toEqual(1);
    expect(wrapped.find('button').length).toEqual(1);
});

it('has a text area that users can type in', () => {
    wrapped.find('textarea').simulate('change', {
        target: {
            value: 'new comment'
        }
    });
    wrapped.update();

    expect(wrapped.find('textarea').prop('value')).toEqual('new comment');
});

我希望得到new comment的输出,但是实际返回的是undefined

2 个答案:

答案 0 :(得分:2)

 handleChange = event => {
    this.setState({
        comment: event.target.value
    })
}

首先进行更改,这是在注释变量中设置值的错误方式

答案 1 :(得分:0)

请尝试下面的方法以及Kishan Jaiswal建议的功能实现:

library(shiny)

if (interactive()) {
  # Define UI
  ui <- fluidPage(
    actionButton("add", "Add UI"),
    actionButton("remove", "Remove UI"),
    uiOutput("textbox"))


  # Server logic
  server <- function(input, output, session) {

    # adding UI
    observeEvent(input$add, 
      output$textbox <- renderUI({
        div(
          textInput("txt", "Insert some text"),
          id="textinput"
          )
      })

    )

    # removing UI
    observeEvent(input$remove, {
      removeUI(selector = "#textinput")
    })
  }

  shinyApp(ui, server)
}