Jest和Enzyme with React:模拟方法与翻译

时间:2017-07-04 16:27:39

标签: reactjs jestjs enzyme

我正在为我正在进行的项目进行一些单元测试,并且我在React上有以下模式。请注意,我通常会传递t进行翻译,我试图在测试中进行翻译,但它正在运行:

import React, { Component } from 'react'
import { Modal, Button } from 'react-bootstrap'
import {translate} from 'react-polyglot'

class MessageModal extends Component {
  render () {
    const {messageModal: {message, isOpen}, closeMessageModal, t} = this.props
    return (
      <Modal show={isOpen}>
        <Modal.Body>
          {message ? t(`MESSAGE_MODAL.${message}`) : ''}
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={closeMessageModal}>Close</Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

export default translate()(MessageModal)

以及以下测试:

import React from 'react'
import MessageModal from './MessageModal'
import { shallow } from 'enzyme'
import { shallowToJson } from 'enzyme-to-json'
// import {translate} from 'react-polyglot'

describe('Testing MessageModal', () => {
  const tree = shallow(
    <MessageModal t={jest.fn()} messageModal={{message: 'message', isOpen: true}}/>
  )
  it('Renders correctly', () => {
    expect(shallowToJson(tree.dive().setProps({t: jest.fn()}))).toMatchSnapshot()
  })
})

我遇到两个主要错误: TypeError: t is not a functionWarning: Failed context type: The context `t` is marked as required in `_translate`, but its value is `undefined`.

我已经尝试了一切来解决这个问题,但我无法让它发挥作用。如果你能帮助我那就太好了。

1 个答案:

答案 0 :(得分:1)

您可以做的是导出未装饰的MessageModal组件。

import React, { Component } from 'react'
import { Modal, Button } from 'react-bootstrap'
import {translate} from 'react-polyglot'

export class MessageModal extends Component {
  render () {
    const {messageModal: {message, isOpen}, closeMessageModal, t} = this.props
    return (
      <Modal show={isOpen}>
        <Modal.Body>
          {message ? t(`MESSAGE_MODAL.${message}`) : ''}
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={closeMessageModal}>Close</Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

export default translate()(MessageModal)

这样您就可以在测试中导入未修饰的组件,这样您就不必处理更高阶的组件部分。

import { MessageModal } from './MessageModal'