【发布时间】:2020-04-26 11:22:34
【问题描述】:
我有以下组件...
export default class TextInput extends PureComponent<TextInputProps> {
private handleOnChange = (event: OnChangeEvent): void => {
if (!this.props.disabled && this.props.onChange) {
this.props.onChange(event)
}
}
private handleOnBlur = (event: OnBlurEvent): void => {
if (!this.props.disabled && this.props.onBlur) {
this.props.onBlur(event)
}
}
public render(): ReactNode {
return (
<Styled.TextInput
id={this.props.id}
type={this.props.type}
onChange={this.handleOnChange}
onBlur={this.handleOnBlur}
disabled={this.props.disabled}
/>
)
}
}
我正在尝试使用以下测试来测试 handleOnChange 函数...
const mockOnChange = jest.fn((): void => { })
const mockOnBlur = jest.fn((): void => { })
const minHandlerProps ={
id: 'test',
type: 'text',
onChange: mockOnChange,
onBlur: mockOnBlur,
}
describe('handleOnChange', () => {
it('Should not call the onChange prop when it\'s been passed and TextInput is disabled', () => {
const wrapper = shallow(<TextInput {...minHandlerProps} disabled={true} />)
const instance = wrapper.instance()
instance.handleOnChange()
expect(minHandlerProps.onChange).not.toHaveBeenCalled()
})
it('Should call the onChange prop when it\'s been passed and TextInput is not disabled', () => {
const wrapper = shallow(<TextInput {...minHandlerProps} />)
const instance = wrapper.instance()
instance.handleOnChange()
expect(minHandlerProps.onChange).toHaveBeenCalled()
})
})
测试按此顺序通过,但如果我围绕 should not call the onChange prop 交换顺序,测试将失败。
这是因为在这种情况下,onChange 属性已经在第一个 it() 中被调用了吗?
我应该为此写一个单独的描述吗?
我已经通过控制台记录了道具正在正确传递,并且看起来好像它们是正确的,所以我对这种行为感到茫然。感谢任何可以对此有所了解的人。
【问题讨论】:
-
@jonrsharpe 谢谢!我无法将您的评论标记为正确答案,但如果您将其添加为答案,我可以在下面将其标记为正确。
标签: javascript reactjs unit-testing jestjs