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

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

问题描述

我需要一些帮助来理解如何使用 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 测试文件.

And here's my test file for 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 />
  </AppContext.Provider>
)

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

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

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