reactjs - enzyme :方法 “text” 仅适用于在单个节点上运行。 0 找到代替

标签 reactjs jestjs enzyme

我正在使用 React v15.4、babel-jest v18 和 enzyme v2.5.1

我有一个简单的 React 组件:

import React, {Component} from 'react'
import {FormattedRelative} from 'react-intl'
import pageWithIntl from '../components/PageWithIntl'
import Layout from '../components/Layout'

class About extends Component {
  static async getInitialProps ({req}) {
    return {someDate: Date.now()}
  }

  render () {
    return (
      <Layout>
        <h1>About</h1>
        <p>
          <FormattedRelative
            value={this.props.someDate}
            updateInterval={1000}
          />
        </p>
      </Layout>
    )
  }
}

export default pageWithIntl(About)

还有一个简单的 Jest/ enzyme 测试:

/* global it, expect, describe */

import React from 'react'
import { shallow } from 'enzyme'
import renderer from 'react-test-renderer'
import About from '../pages/about.js'

describe('With Enzyme', () => {
  it('App shows "About"', () => {
    const about = shallow(
      <About />
    )
    expect(about.find('h1').text()).toEqual('About')
  })
})

Jest 测试应该通过,但我收到错误:

Method “text” is only meant to be run on a single node. 0 found instead.

我错过了什么?

===更新

快照测试通过:

describe('With Snapshot Testing', () => {
  it('About shows "About"', () => {
    const component = renderer.create(<About />)
    const tree = component.toJSON()
    expect(tree).toMatchSnapshot()
  })
})

有没有办法将 enzyme 预期测试集成到快照测试中?又如何?

最佳答案

这是由于浅层不渲染子组件并且您的组件被函数包装的事实造成的。如此浅层仅返回函数的表示而不是组件的表示。 您可以使用dive()到达真正的组件

/* global it, expect, describe */

import React from 'react'
import { shallow } from 'enzyme'
import renderer from 'react-test-renderer'
import About from '../pages/about.js'

describe('With Enzyme', () => {
  it('App shows "About"', () => {
    const about = shallow(
      <About />
    ).dive()
    expect(about.find('h1').text()).toEqual('About')
  })
})

关于reactjs - enzyme :方法 “text” 仅适用于在单个节点上运行。 0 找到代替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43073338/

相关文章:

javascript - 如何解决 react 类型错误: Cannot read properties of undefined (reading 'name' )

reactjs - 无法与 Looker 主机建立通信

javascript - Jest 与 enzyme |在 componentDidMount 中测试 PropTypes 函数

reactjs - 如何在 webpack 中使用 jest?

reactjs - 使用 Enzyme 和 Jest 在 React 中测试 handle change 函数

reactjs - 将 React useState 与 Sinon 打桩

javascript - 如何正确删除 React 状态数组中的元素?

javascript - 在Reactjs中根据条件导入组件(Conditional based import)

reactjs - 用jest测试Echarts React组件,EchartElement为null

reactjs - SecurityError : replaceState cannot update history to a URL which differs in components other than in path, 查询或片段