JEST/酶类组件测试中的反应暂停和反应延迟子组件

本教程将介绍JEST/酶类组件测试中的反应暂停和反应延迟子组件的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

JEST/酶类组件测试中的反应暂停和反应延迟子组件 教程 第1张

问题描述

因此,我将类组件中使用的导入转换为React.lazy导入API,并将其包装在一个挂起标记中。当我测试那个类组件时,酶抛出一个错误"Enzyme Internal Error: unknown node with tag 13"。是否有一种方法可以呈现和测试延迟加载组件的装载,而不是使用浅层呈现?

我已经尝试了异步等待,直到延迟加载的承诺解决,但也不起作用,如下所示:

it('async await mount', () async () => {
  const wrapper = await mount(<Component />)
}

以下是示例代码:

Component.js

import React, { PureComponent, Suspense } from 'react'

const ChildComponent = React.lazy(() => import('../ChildComponent'))

export default class Component extends PureComponent {
  constructor() {
super()
this.state = {
 example: null
}
  }

  doSomething = () => this.setState({
example: 'example'
  })

  render() {
 return (
<div>
  <p>Example</p>
  <Suspense fallback={<div>...loading</div>}>
<ChildComponent 
example={this.state.example}
doSomething={this.doSomething}
/>
  </Suspense>
</div>
 )
  }
}

Component.test.js

import React from 'react'
import renderer from 'react-test-renderer'
import { mount } from 'enzyme'
import Component from '../../Component'

describe('Component', () => {
 // snapshot renders loading and not children
 it('example snapshot of tree', () => {
  const tree = renderer.create(<Component />).toJSON()
  expect(tree).toMatchSnapshot()
 })

 it('example mount test', () => {
  // this test fails and throws error I state above
  const wrapper = mount(<Component />)
  wrapper.setState({ example: 'example' })
  expect(wrapper.state.example).toBe('example')
 })
})

我读到酶还不支持Reaction 16.6 Suspense API,但我想知道是否还有方法测试挂载的,以便我可以使用酶的simulatefindAPI。

推荐答案

解决方案

ChuckJHardy链接的GitHub问题已解决、合并并发布。从1.14.0开始,您可以在酵素中使用挂载API。

引用

好了关于JEST/酶类组件测试中的反应暂停和反应延迟子组件的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。