I started a new "Hello World" project on react which looks like that:
import React, { Component } from 'react';
export class Home extends Component {
displayName = Home.name
state = {
result: 0,
val1: 0,
val2: 0,
}
handleChangeOne = (event) => {
this.setState({ val1: event.target.value });
}
handleChangeTwo = (event) => {
this.setState({ val2: event.target.value });
}
add = () => {
this.setState({
result: parseInt(this.state.val1) + parseInt(this.state.val2)
});
}
render() {
return (
<div>
<h1>Hello world! The result is: {this.state.result}</h1>
<input type="text" onChange={this.handleChangeOne} />
+
<input type="text" onChange={this.handleChangeTwo} />
= <br />
<button onClick={this.add}>Add</button>
</div>
);
}
}
Basically, the user insert two numbers and when he clicks the "Add" button, the result will appear on the screen.
When I run the component, it seems to work but I want to test it with Jest (Also to get familiar with Jest).
I have installed Jest and reviewed all the steps on their website but I am still not sure how should I write the test.
Inside the test, I want to insert two numbers (same as the user does) and check that it returns their sum.
So far I created a new file "Home.test.js" which is kind of a pseudo code for the test I want to perform.
Of course it's not working now but I would love to make it work.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Home } from './Home.js';
it('Returns a sum', () => {
const home = shallow(<Home />);
var first_val = Home.state.val1;
var second_val = Home.state.val2;
var result = first_val + second_val;
expect(result).toEqual(Home.state.result);
});
Thanks in advance.
Code:
You may find it useful.
1.Remember to access state you have to call state() like this.
2.You have already made a wrapper from here.
Now accessing state like this is wrong.
3.By default the state contains default values.
4.To give the input values to field .First find the field and simulate the onchange as below.
5.Now to add these values call the add button.
6.Your job is not done !Don't forget to call this.
7.Now check the value