>我在 TDD 过程中遇到了问题,反应钩子的状态没有按预期改变
标题.tsx
import React, { useState, ChangeEvent, KeyboardEvent } from 'react';
interface Props {
addUndoItem: (item: string) => void;
}
function Header(props: Props) {
const [value, setValue] = useState('');
const handleChange = (e: ChangeEvent<{ value: string }>) => {
setValue(e.target.value);
};
const handleKeyUp = (e: KeyboardEvent) => {
if (value && e.keyCode === 13) {
props.addUndoItem(value);
}
};
return (
<div>
<input
onChange={handleChange}
onKeyUp={handleKeyUp}
value={value}
data-test="input"
/>
</div>
);
}
test/Header.tsx
it('the fn may invoked when press enter', () => {
const userInput = 'test';
const fn = jest.fn();
const wrapper = shallow(<Header addUndoItem={fn} />);
const inputEle = wrapper.find('[data-test="input"]');
inputEle.simulate('change', {
target: {
value: userInput
}
});
inputEle.simulate('keyUp', {
keyCode: 13
});
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledWith(userInput);
});
当exec模拟更改时,Header钩子中的值仍然''
应该是test
,它在浏览器中运行成功
错误是
expect(jest.fn(((.toHaveBeenCalled((
Expected number of calls: >= 1
Received number of calls: 0
48 | keyCode: 13
49 | });
> 50 | expect(fn).toHaveBeenCalled();
| ^
51 | expect(fn).toHaveBeenCalledWith(userInput);
52 | });
53 |
您需要使用mount
而不是shallow
,否则您的input
组件将无法正确呈现,因此在测试期间无法使用。