这是我的考验
describe('MultipleDaySelector', () => {
test('checked the MultipleDaySelector', () => {
const propVal = ''
const { container } = render(<MultipleDaySelector parentCallbackMultipleDaySelector={propVal} />)
const checkBoxes = container.querySelector('[type="checkbox"]') as HTMLElement
expect(checkBoxes).not.toBe(null);
act(() => {
userEvent.click(checkBoxes)
});
expect(checkBoxes).toBeChecked()
})
})
export default function MultipleDaySelector({ parentCallbackMultipleDaySelector }): JSX.Element {
const onChange = (value) => parentCallbackMultipleDaySelector(value)
return <>
<Checkbox.Group
data-testid="MultipleDaySelectorTest"
onChange={onChange}
name="MultipleDaySelector"
options={[
{ label: "Monday", value: "1" },
{ label: "Tuesday", value: "2" },
{ label: "Wednesday", value: "3" },
{ label: "Thursday", value: "4" },
{ label: "Friday", value: "5" },
{ label: "Saturday", value: "6" },
{ label: "Sunday", value: "0" }
]}
/>
</>
}
如您所见,我将要测试MultipleDaySelector函数,当我运行测试时,我会报错
TypeError: parentCallbackMultipleDaySelector is not a function
3 |
4 | export default function MultipleDaySelector({ parentCallbackMultipleDaySelector }): JSX.Element {
> 5 | const onChange = (value: any) => parentCallbackMultipleDaySelector(value)
| ^
6 |
7 | return <>
8 | <Checkbox.Group
当我删除parentCallbackMultipleDaySelector测试正常时,但是我不知道回调函数有什么问题
答案 0 :(得分:0)
问题:您正在传递字符串(而不是函数)作为测试中的道具
describe('MultipleDaySelector', () => {
test('checked the MultipleDaySelector', () => {
const propVal = '' // <-- This is a string!!
const { container } = render(<MultipleDaySelector parentCallbackMultipleDaySelector={propVal} />)
const checkBoxes = container.querySelector('[type="checkbox"]') as HTMLElement
expect(checkBoxes).not.toBe(null);
act(() => {
userEvent.click(checkBoxes)
});
expect(checkBoxes).toBeChecked()
})
})
函数中的这一行强制道具parentCallbackMultipleDaySelector
必须是一个函数:
const onChange = (value) => parentCallbackMultipleDaySelector(value)
解决方案::传递一个函数,即() => {}
或jest.fn()
describe('MultipleDaySelector', () => {
test('checked the MultipleDaySelector', () => {
const propVal = jest.fn();
const { container } = render(<MultipleDaySelector parentCallbackMultipleDaySelector={propVal} />)
const checkBoxes = container.querySelector('[type="checkbox"]') as HTMLElement
expect(checkBoxes).not.toBe(null);
act(() => {
userEvent.click(checkBoxes)
});
expect(checkBoxes).toBeChecked()
})
})