-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
node
version: 12.13.0yarn
version: 1.19.1react-testing-library
version: 9.3.2react
version: 16.12.0redux
: 4.0.4react-redux
: 7.1.3,react-scripts
: 3.2.0
Relevant code or config / minimal steps to reproduce:
Create a base app with npx create-react-app myapp
.
Install also redux, react-redux, @testing-library/react (in devDependencies).
In the App.js file:
class App extends React.Component {
onClick = () => {
this.props.dispatch({ type: '', data: { } })
}
render() {
return <div className="App" onClick={this.onClick}>{this.props.count}</div>
}
}
export default connect((s, p) => s)(App)
In the App.test.js
file and write this:
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './App'
import { createStore } from 'redux'
import { fireEvent, render } from '@testing-library/react'
function createAppStore() {
let initialState = { count: -1 }
function reducer(state = initialState, action) {
return { count: state.count + 1 }
}
let store = createStore(reducer)
return store
}
describe('App tests', () => {
let store
let container
let div
beforeAll(() => {
store = createAppStore()
container = render(<Provider store={store}><App /></Provider>)
div = container.baseElement.querySelector('.App')
})
it('renders without crashing', () => {
})
it('initially is 0', () => {
expect(div.innerHTML).toBe('0')
})
it('clicked is 1', () => {
// container = render(<Provider store={store}><App key={1} index={1}/></Provider>)
// div = container.baseElement.querySelector('.App')
fireEvent.click(div)
expect(div.innerHTML).toBe('1')
})
})
What you did:
Run yarn test
(to start the jest tests through react-scripts).
What happened:
The last test fails: the content is not '1' as expected, but '0'. Like the click was never raised.
Now, if I de-comment the two commented lines just before the expect(), the test passes.
Problem description:
I can't use beforeAll()
to create and configure my component once.
I have to re-write the render() part in every single it() test. If I have 10 it(), it's an awkward duplication of code.
Why is this happening? Why the rendered component changes from it() to it()?
Is there something I can do?
Is there a workaround?
Suggested solution:
None.