首页 文章

酶:方法“text”仅用于在单个节点上运行 . 0找到了

提问于
浏览
7

我正在使用React v15.4,babel-jest v18和酶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测试应该通过,但我收到一个错误:

方法“text”仅用于在单个节点上运行 . 0找到了 .

我错过了什么?

===更新

快照测试通过:

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

有没有办法在快照测试中整合酶期望测试?如何?

3 回答

  • 6

    它的原因是浅层不会渲染子组件并且您的组件被函数包裹 . 如此浅只返回函数的表示而不是组件的表示 . 您可以使用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')
      })
    })
    
  • 0

    请参阅此链接,了解如何在浅拷贝上使用.findWhere:https://blogs.sequoiainc.com/an-enzyme-gotcha/

    下面是一个示例,查找类型为“p”的节点/ html元素,其中包含表示工资“$ 100,000.00”的所需文本 .

    displayemployee = shallow(<DisplayEmployee employeeData={employee}
    
    it('renders the employees salary', () => {
      expect(
        displayemployee.findWhere(
        n => n.type() === 'p' && n.contains('$100,000.00')
      )
    )
    

    浅拷贝返回react组件返回的所有节点,我用.findWhere而不是.text搜索这些节点 . 这是因为.text期望查看单个节点; .text不知道如何扫描多个节点 .

  • 2

    Use .first()

    示例const wrapper = shallow()

    wrapper.find('h1或p或.ClassName或#id') . first();

    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').first().text()).toEqual('About')
     })
    })
    

相关问题