6

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
  })
})

以下是测试结果: 在此处输入图像描述

这是我的版本:

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

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

4

0 回答 0