笑话模拟反应上下文 [英] Jest mock react context

查看:165
本文介绍了笑话模拟反应上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,以了解如何使用React Context测试应用程序.

I need some help understanding how one can test an application using React Context.

这是我的示例设置.

context.js

import React from 'react'

export const AppContext = React.createContext()

App.js

import React from 'react'

import MyComponent from './MyComponent'
import {AppContext} from './context'

const App extends React.Component {

  state = {
    items: []
  }

  handleItemAdd = newItem => {
    const {items} = this.state
    items.push(newItem)
    this.setState(items)
  }

  render() {
    return (
      <AppContext.Provider value={{
        addItem: this.handleItemAdd
      }}>
        <MyComponent />
      </AppContext.Provider>
    )
  }
}

export default App

MyComponent.js

import React from 'react'

import {AppContext} from './context'

const MyComponent extends React.Component {    
  render() {
    return (
      <AppContext.Consumer>
        {addItem => 
          <button onClick={() => addItem('new item')}>
            Click me
          </button>
        }
      </AppContext.Consumer>
    )
  }
}

export default MyComponent

这是一个简化的示例.想象在AppMyComponent之间有更多的层,因此使用React Context.

This is a simplified example. Imagine that there are more layers between App and MyComponent, hence the use of React Context.

这是我的MyComponent测试文件.

MyComponent.test.js

import React from 'react'
import {render, fireEvent} from 'react-testing-library'

test('component handles button click', () => {
  const {getByText} = render(
    <MyComponent />
  )
  const button = getByText('Click me')
  fireEvent.click(button)
  expect...?
}

问题是,AppContext.ConsumerMyComponent的实现的一部分,因此在此测试中,我无法直接访问它.如何模拟AppContext.Consumer,以便实际上可以验证单击按钮会触发函数调用?

The thing is, AppContext.Consumer is part of the implementation of MyComponent, so in this test I don't have direct access to it. How do I mock AppContext.Consumer so I am actually able to verify that clicking a button fires a function call?

我知道理论上可以通过在App中渲染MyComponent来进行测试,但是我只想为MyComponent编写单元测试.

I know that in theory I can test this by rendering MyComponent in my App, but I want to write a unit test for MyComponent only.

推荐答案

您只需使用组件呈现上下文即可.

You just render the context with your component.

const addItem = jest.fn()
render(
  <AppContext.Provider value={{ addItem }}>
    <MyComponent />
  </ApppContext.Provider>
)

请参见使用react-testing-library模拟上下文

这篇关于笑话模拟反应上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆