I'm trying to get my head around functional testing in React and I've hit a bit of a blocker which I wish someone can shed some light on. Currently, I have a little counter application which has a button component that receives a function and a string as props. that looks like this:
Button.js
import React from 'react'
import PropTypes from 'prop-types'
export const Button = (props) => {
const { btnTitle, btnAction } = props
return (
<button onClick={btnAction}>{btnTitle}</button>
)
}
Button.propTypes = {
btnAction: PropTypes.func,
btnTitle: PropTypes.string
}
I also have a helpers directory that contains my CounterHandler function which receives a number as the counter initial value and can either increase or decrease said initial value. The code looks as follows:
CounterHandler.js
import React from 'react'
export const CounterHandler = num => {
const [counter, setCounter] = React.useState(num)
const increase = () => setCounter(counter + 1)
const decrease = () => setCounter(counter - 1)
return {
counter,
increase,
decrease
}
}
now my App.js which renders the button and the action code looks like this.
App.js
import React from 'react'
import CounterHandler from './components/button/helpers'
import Button from './components/button'
function App () {
const counter = CounterHandler(0)
return (
<div className="App">
<Button btnTitle="click to increase" btnAction={counter.increase} />
<Button btnTitle="click to decrease" btnAction={counter.decrease} />
<h1>counter: {counter.counter}</h1>
</div>
)
}
export default App
The application works as it's intended. The counter will increase or decrease based on which button was pressed.
Now I'm attempting to write a test for my CounterHandler.js function, but unfortunately, I keep hitting a hooks error that does not occur when running the application on my local server.
So far the only test I wanted to try is to get the initial value found in my counter and continue from there. My test looks like this:
CounterHandler.test.js
import { CounterHandler } from './CounterHandler'
const counter = CounterHandler(0)
describe('Counter state', () => {
test('test initial state', () => {
expect(counter.counter).tobe(0)
})
})
and the output I'm getting is:
Can someone give me some pointers? I would greatly appreciate it.
for a further look into my configs, this is my experimental GitHub account for this project. https://github.com/melvinalmonte/testing-practice
Thanks!!
