import React from 'react'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
import { render, fireEvent, cleanup } from '@testing-library/react'
class Counter extends React.Component {
increment = () => {
this.props.dispatch({ type: 'INCREMENT' })
}
decrement = () => {
this.props.dispatch({ type: 'DECREMENT' })
}
render() {
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span data-testid="count-value">{this.props.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
)
}
}
const ConnectedCounter = connect(state => ({ count: state.count }))(Counter)
function reducer(state = { count: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1,
}
case 'DECREMENT':
return {
count: state.count - 1,
}
default:
return state
}
}
afterEach(cleanup)
function renderWithRedux(
ui,
{ initialState, store = createStore(reducer, initialState) } = {}
) {
return {
...render(<Provider store={store}>{ui}</Provider>),
store,
}
}
test('can render with redux with defaults', () => {
const { getByTestId, getByText } = renderWithRedux(<ConnectedCounter />)
fireEvent.click(getByText('+'))
expect(getByTestId('count-value').textContent).toBe('1')
})
test('can render with redux with custom initial state', () => {
const { getByTestId, getByText } = renderWithRedux(<ConnectedCounter />, {
initialState: { count: 3 },
})
fireEvent.click(getByText('-'))
expect(getByTestId('count-value').textContent).toBe('2')
})
test('can render with redux with custom store', () => {
const store = createStore(() => ({ count: 1000 }))
const { getByTestId, getByText } = renderWithRedux(<ConnectedCounter />, {
store,
})
fireEvent.click(getByText('+'))
expect(getByTestId('count-value').textContent).toBe('1000')
fireEvent.click(getByText('-'))
expect(getByTestId('count-value').textContent).toBe('1000')
})