我在TDD过程中遇到了一个问题,反应挂钩的状态没有按预期改变
// Header.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>
);
}
// 测试 /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 |
答案 0 :(得分:0)
您需要使用mount
而不是shallow
,否则您的input
组件将无法正确呈现,因此在测试期间将无法使用。