反应测试库fireEvent.change无法与fireEvent.submit一起使用

时间:2019-03-19 16:14:42

标签: reactjs testing mocha react-testing-library

tldr; fireEvent.change有效,但在表单提交时,在提交处理程序中找不到新值。

说我们有一个简单的表格:

// MyForm.tsx
class MyForm extends React.Component {
  state = { data: '123' }
  handleChange = (e: any) => {
    // This never gets fired in the test, why?
    console.log('HandleChange Fired', e.target.value)
    this.setState({ data: e.target.value })
  }
  handleSubmit = () => {
    console.log('************* HandleSubmit Fired **************', this.state)
  }
  render() {
    return (
      <form name="address" onSubmit={this.handleSubmit}>
        <input name="title" value={this.state.data} onChange={this.handleChange} />
        <button type="submit">Submit</button>
      </form>
    )
  }
}

和断言表单提交值的测试是准确的:

// MyForm.spec.tsx
import React from 'react'
import { expect } from 'chai'
import { fireEvent, render, wait } from 'react-testing-library'
import { JSDOM } from 'jsdom'
import MyForm from './MyForm'
 .
const dom = new JSDOM('<!doctype html><html><body><div id="root"><div></body></html>')
global.document = dom.window.document
global.window = dom.window
global.navigator = dom.window.navigator
.
describe.only('MyForm works!', () => {
  it('Should change the value of the field', async () => {
    const { container, debug } = render(<MyForm />)
    const field: any = container.querySelector('input[name="title"]')
.
    // Change the value
    fireEvent.change(field, { target: { value: 'Hello World!' } })
    expect(field.value).to.equal('Hello World!') // true
.
    console.log('Field value: ', field.value) // prints 'Hello World!'
    debug(field) // html is printed out in console, shows old value unexpectedly.
.
    // Submit the form
    const form: any = container.querySelector('form[name="address"]')
    const onSubmit = fireEvent.submit(form)
    expect(onSubmit).to.equal(true) // true, but form submit value is still the old one
  })
})

以下是测试结果: enter image description here

这是我的版本:

"jsdom": "^11.5.1",
"mocha": "^5.1.1",
"react": "^16.8.4",
"react-testing-library": "^6.0.0"
"dom-testing-library": "3.17.1"

如何在onChange之后获取表单handleSubmit值以反映新的输入值?

0 个答案:

没有答案