tldr; fireEvent.change works, but on form submit, new value not found in submit handler.
Say we have a simple form:
// 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>
)
}
}
and a test to assert the form submission values are accurate:
// 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
})
})
Here are my versions:
"jsdom": "^11.5.1",
"mocha": "^5.1.1",
"react": "^16.8.4",
"react-testing-library": "^6.0.0"
"dom-testing-library": "3.17.1"
How do I get the form handleSubmit value to reflect the new input value after the onChange?

Aucun commentaire:
Enregistrer un commentaire