跳至主要内容

useReducer

基本示例展示如何测试 useReducer 钩子。最重要的是我们不直接测试 reducer - 它是组件的实现细节!相反,我们测试组件接口。

我们正在测试的组件根据 isConfirmed 状态更改一些文本。

// example.js

import React, {useReducer} from 'react'

const initialState = {
isConfirmed: false,
}

function reducer(state = initialState, action) {
switch (action.type) {
case 'SUCCESS':
return {
...state,
isConfirmed: true,
}
default:
throw Error('unknown action')
}
}

const Example = () => {
const [state, dispatch] = useReducer(reducer, initialState)

return (
<div>
<div>
{state.isConfirmed ? (
<p>Confirmed!</p>
) : (
<p>Waiting for confirmation...</p>
)}
</div>
<button onClick={() => dispatch({type: 'SUCCESS'})}>Confirm</button>
</div>
)
}

export default Example

我们正在测试根据 reducer 状态,我们在 JSX 中是否获得了正确的输出。

// example.test.js

import React from 'react'
import {render, fireEvent} from '@testing-library/react'
import Example from './example.js'

it('shows success message after confirm button is clicked', () => {
const {getByText} = render(<Example />)

expect(getByText(/waiting/i)).toBeInTheDocument()

fireEvent.click(getByText('Confirm'))

expect(getByText('Confirmed!')).toBeInTheDocument()
})