![](/img/trans.png)
[英]Follow DRY principles while writing jest mocks in test cases - React and Jest
[英]Writing Test Cases with Jest in React
我想為下面的代碼編寫Jest測試用例。我是編寫測試的新手。 誰能給我個提示。 我有jest-enzyme和jest-cli運行,我想用純正的jest編寫。
下面是我要編寫的代碼,除了DOM檢查外,我還需要檢查即將到來的值,或者是否還需要為其他事情編寫UT?
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;
您可以在單元測試中檢查多種內容。 您可以使用Jest的代碼覆蓋功能來確定測試中實際覆蓋了代碼的哪些行和分支。
這可能是一個開始(可能缺少一些必要的道具來彌補您的組件):
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')
)}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.