用Jest和酶反应测试用例

时间:2020-05-11 18:16:07

标签: javascript reactjs unit-testing jestjs enzyme

我是为React写测试用例的新手。有人可以告诉我如何继续编写该文件的测试用例以及如何完成代码覆盖范围。

我如何测试下面的mapDispatchToProps,componentDidMount或handleClick函数。有人可以向我解释如何进行测试用例的步骤。

import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import DOMPurify from 'dompurify'
import escape from 'escape-html'

import Message from 'wf-dbd-react-ui/es/Message'
import ContentEventWrapper from 'wf-dbd-react-ui/es/ContentEventWrapper'
import { unescapeHtml } from 'wf-dbd-react-ui/es/lib'
import { requestNavigation } from 'wf-dbd-react-ui/es/actions'
import NavigationItemRecord from 'wf-dbd-react-ui/es/lib/records/NavigationItemRecord'
import ScrollToTopOnMount from 'wf-dbd-react-ui/es/ScrollToTopOnMount'

class MessageDisplayWithSpecialCharacters extends Component { //NOSONAR

  constructor(props) {
    super(props)
    this.elementRef = null
  }

  componentDidMount() {
    if (this.props.focusOnMount) {
      if (this.elementRef) {
        this.elementRef.blur() //needed to reset focus in iOS
        this.elementRef.focus()
        setTimeout(() => { this.elementRef.focus() }, 100) //timeout needed for Android
      }
    }
  }

  setElementRef = element => {
    this.elementRef = element
  }

  handleClick = ({ target }) => {
    const { requestNavigation } = this.props
    if (target.hasAttribute('data-cui-link')) {
      const navigationItem = new NavigationItemRecord({
        samlNavigation: true,
        displayType: 'saml',
        navigationUrl: target.getAttribute('data-cui-link')
      })
      requestNavigation(navigationItem)
    }
  }

  render() {
    const { messages, className } = this.props
    return (
      <div className={className} tabIndex="-1" ref={this.setElementRef}>
        <ScrollToTopOnMount />
        {messages.map((message, index) => {
          const purifiedContent = { __html: DOMPurify.sanitize(unescapeHtml(JSON.parse(`"${escape(window.decodeURIComponent(message.get('message')))}"`))) }
          return (
            <ContentEventWrapper handleContentClick={this.handleClick} key={index}>
              <Message announce={true} level={message.get('level')}>
                <p dangerouslySetInnerHTML={purifiedContent} />
              </Message>
            </ContentEventWrapper>
          )
        })}
      </div>
    )
  }
}

MessageDisplayWithSpecialCharacters.propTypes = {
  messages: PropTypes.array,
  className: PropTypes.string,
  focusOnMount: PropTypes.bool,
  requestNavigation: PropTypes.func
}

const mapDispatchToProps = dispatch => ({
  requestNavigation: navigationItem => dispatch(requestNavigation(navigationItem))
})

export default connect(null, mapDispatchToProps)(MessageDisplayWithSpecialCharacters)

任何帮助/建议都对像我这样的新手表示赞赏。

0 个答案:

没有答案