在React中用Jest编写测试用例

时间:2018-06-22 11:25:30

标签: reactjs jestjs

我想为下面的代码编写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;

1 个答案:

答案 0 :(得分:2)

您可以在单元测试中检查多种内容。您可以使用笑话的代码功能{coverage来确定测试中实际覆盖了代码的哪些行和分支。

这可能是一个开始(可能缺少一些您的组件所需的道具):

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')
  )}

})