![](/img/trans.png)
[英]How to test onClick functionality which is present in parent component (arrow function)?
[英]How to test onClick which programmatically fires file input
我對測試很陌生。 我想測試我的onClick
function 是否正常發射。
onClick
function 的行為是以編程方式觸發文件輸入。
const Component = () => {
const onBtnClick = (e: SyntheticEvent) => {
e.stopPropagation();
inputFileRef?.current?.click();
};
return (
<Box data-testid="upload-wrapper">
<input
data-testid="upload-input"
type="file"
hidden
ref={inputFileRef}
onChangeCapture={onFileChangeCapture}
accept="image/jpeg,image/png,image/jpg"
tabIndex={-1}
/>
<Button data-testid="upload-btn" onClick={onBtnClick}>
Upload image
</Button>
)
}
我從react-dropzone
測試源文件中找到了解決方案。 至少它適用於我的情況。 這是關於以編程方式打開文件對話框的鏈接react-dropzone@src/index.spec.js 。
我的代碼:
it('Should open file dialog', () => {
const onClickSpy = vi.spyOn(HTMLInputElement.prototype, 'click');
renderScreen({});
fireEvent.click(screen.getByTestId('image-upload-btn'));
expect(onClickSpy).toHaveBeenCalled();
});
[1]: https://github.com/react-dropzone/react-dropzone/blob/master/src/index.spec.js#L3371
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.