I'm new in React Enzyme testing. I want to simulate input/change action.
Second test failed although input '#num1' is found:
Expected value to equal: "23"
Received: "undefined"
I tried using 'text()' instead of 'value', then return "".
Also I wrote a test which look for button text and passed return '+'.
When I remove one of two inputs and find 'input', also return 'undefined'.
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component{
constructor(){
super();
this.state = {
number1: 0,
number2: 0,
result: 0
}
}
render(){
return(
<div>
<div>
<label>Number 1</label>
<input id="num1" onInput={this.rememberNumber1.bind(this)} />
<br/><br/>
<label>Number 2</label>
<input id="num2" onInput={this.rememberNumber2.bind(this)} />
</div>
<div>
<h1>{this.state.number1}+{this.state.number2}={this.state.result}</h1>
</div>
<div>
<button id="an" onClick={this.sum.bind(this)}>+</button>
<button onClick={this.subtract.bind(this)}>-</button>
<button onClick={this.multiply.bind(this)}>*</button>
<button onClick={this.divide.bind(this)}>:</button>
</div>
</div>
)
}
rememberNumber1(e){
if (e.target.value==""){
this.setState({
number1: 0
})
}
else {
this.setState({
number1: e.target.value
})
}
}
rememberNumber2(e){
if (e.target.value==""){
this.setState({
number2: 0
})
}
else {
this.setState({
number2: e.target.value
})
}
}
sum(e){
this.setState({
result: Number(this.state.number1)+Number(this.state.number2)
})
}
subtract(e){
this.setState({
result: Number(this.state.number1)-Number(this.state.number2)
})
}
multiply(e){
this.setState({
result: Number(this.state.number1)*Number(this.state.number2)
})
}
divide(e){
this.setState({
result: Number(this.state.number1)/Number(this.state.number2)
})
}
}
export default App;
setupTests.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import App from './App';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
it('includes input', () => {
const app = shallow(<App />);
expect(app.containsMatchingElement(<input/>)).toEqual(true)
});
it('on input', () => {
const wrapper = mount(<App />);
wrapper.find('#num1').simulate('change', {target: {value: 23}})
expect(wrapper.find('#num1').value).toEqual('23')
});
Aucun commentaire:
Enregistrer un commentaire