我有要测试的组件,我无法在其任何内部方法上使用spyOn,因为我无法访问它们。
我正在学习本教程TDD With React, Jest, and Enzyme
但是我想使计算器发挥作用,因为我想了解更多它是如何工作的,以便将来使用挂钩。
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;
这是测试 我无法直接到达updateDisplay,所以我得到了键盘道具(当我将其传递给该组件)并从那里进行模拟,但这似乎是错误的方式,任何人都有办法做得更好或建议更好模拟该功能的方式。
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);
});
});
谢谢。