Reputation:
I want to write Jest Test case for the below code.I am new to writing test. Can anyone give me a heads up. I have jest-enzyme and jest-cli running and i want to write in pure jest.
Below is the code i am trying to write about so apart from DOM check i need to check what values are coming or do i need to write UT for other things also?
import React, { Component } from 'react';
class Message extends Component {
constructor(props) {
super(props);
}
render() {
let i =1;
return(
<div className="message-main-div">
<li className={`chat ${this.props.user === this.props.chat.username ? "right" : "left"}`}>
<div className="chat-timestamp">{this.props.chat.timestamp}</div>
{this.props.user !== this.props.chat.username && <img className="avatar-img" src={this.props.chat.img} alt={`${this.props.chat.username}'s profile pic`} />}
<div className="chat-text"><p>{this.props.chat.content}</p></div>
</li>
{this.props.user != this.props.chat.username &&
this.props.chat.buttons.map((button) => {
return <div key={i++} className="buttons-wrapper-div"><button className="response-button"onClick={this.props.onClick.bind(this, button)}>{button}</button></div>
})
}
</div>
)
}
}
export default Message;
Upvotes: 0
Views: 1085
Reputation: 5926
You have multiple things you can check in the unit test. You can use code-coverage functionality of jest to figure out, which lines and branches of your code are actually covered by tests.
This could be a start (there might be some required props for your component missing):
import {shallow} from 'enzyme'
import Message from '../components/Message'
describe('The Message component', () => {
it('should render li.chat.left when props.user !== props.chat.username', () => {
const wrapper = shallow(<Message user='foo' chat={{username: 'bar', buttons: []}} />)
expect(wrapper.find('li.chat.left').length).toEqual(1)
expect(wrapper.find('li.chat.right').length).toEqual(0)
})
it('should render li.chat.right when props.user === props.chat.username', () => {
const wrapper = shallow(<Message user='foo' chat={{username: 'foo', buttons: []}} />)
expect(wrapper.find('li.chat.left').length).toEqual(0)
expect(wrapper.find('li.chat.right').length).toEqual(1)
})
it('should render the chat.timestamp prop as .chat-timestamp', () => {
const wrapper = shallow(<Message chat={{timestamp: '1234', buttons: []}} />)
expect(wrapper.find('.chat-timestamp').text()).toEqual('1234')
)}
})
Upvotes: 2