Questions and Help
I have this component I wanna test and I cant use spyOn on any of its internal methods as I can't reach them.
I was going along this tutorial TDD With React, Jest, and Enzyme
but I wanted to make the Calculator functional as i wanna learn more how it works in order to use hooks in the future.
import React, {useState} from 'react';
import './Calculator.css';
import Display from "../Display/Display";
import Keypad from "../Keypad/Keypad";
const Calculator = () => {
// value to be displayed in <Display />
const [displayValue, setDisplayValue] = useState('0');
// values to be displayed in number <Keys />
const [numbers, setNumbers] = useState(['9', '8', '7', '6', '5', '4', '3', '2', '1', '.', '0','ce']);
// values to be displayed in operator <Keys />
const [operators, setOperators] = useState(['/', 'x', '-', '+']);
// operator selected for math operation
const [selectedOperator, setSelectedOperator] = useState('');
// stored value to use for math operation
const [storedValue, setStoredValue] = useState('');
const callOperator = () => {
console.log('call operation');
};
const setOperator = () => {
console.log('set operation');
};
const updateDisplay = () => {
console.log('update display');
};
return(
<div className="calculator-container" >
<Display displayValue={displayValue} />
<Keypad
callOperator={callOperator}
numbers={numbers}
operators={operators}
setOperator={setOperator}
updateDisplay={updateDisplay}
/>
</div>
);
};
export default Calculator;
here's the test I can't reach the updateDisplay directly so I get the Keypad props (as I am passing it to that component) and mock it from there but it seems to be the wrong way, anyone has a way to do it better or suggest a better way to mock that function.
describe('mounted <Calculator />', () => {
let wrapper;
let keypad;
beforeEach(() => {
wrapper = mount(<Calculator/>);
keypad = wrapper.find(Keypad);
});
it('calls updateDisplay when a number key is clicked', () => {
const spy = jest.spyOn(wrapper.find(Keypad).props(), 'updateDisplay');
wrapper.update();
expect(spy).toHaveBeenCalledTimes(0);
wrapper.find('.number-key').first().simulate('click');
expect(spy).toHaveBeenCalledTimes(1);
});
});
Thanks in advance.