【发布时间】:2022-01-13 12:59:52
【问题描述】:
我正在构建一个具有输入“文件”类型元素的 React 组件。
export default function NavBar() {
return (
<label htmlFor='upload-image' className={classes.label}> Upload </label>
<input type='file'
id='upload-image'
onChange={ (e) => { uploadImage(e) } } />
)
}
uploadImage是一个独立的函数,从uploadImage.js导出:
// uploadImage.js
const uploadImage = async (e) => {
// some code to upload the image to a cloud database
}
export { uploadImage };
使用 Jest 和 React 测试库,我正在尝试测试是否会在输入“文件”类型元素发生更改时触发 uploadImage。以下是我到目前为止的工作:
import * as uploadImage from '../api/uploadImage';
test("when user changes the file input, uploadImage function is called once", () => {
render( <NavBar /> );
const fileInput = screen.getByLabelText(/Upload/i);
fireEvent.change(fileInput, {
target: {
files: [new File(['(⌐□_□)'], 'chucknorris.png', {type: 'image/png'})],
},
});
const mock = jest.spyOn(uploadImage, 'uploadImage');
expect(mock).toBeCalled();
});
我希望测试通过。当 fireEvent.change() 被启动时,uploadImage 应该被启动。但是测试失败,说明uploadImage没有被初始化如下:
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
我怀疑 fireEvent.change() 不起作用,但我不确定。 \
- 您能解释一下为什么测试没有通过吗?
- 对于
uploadImage.js,如果我使用导出默认值,即export default uploadImage,我应该如何使用jest来模拟uploadImage,而不是写export { uploadImage }?
非常感谢!
【问题讨论】:
-
您可能需要等待事件生效。尝试使用
waitFor -
嗨@tromgy,感谢您的快速回答!不幸的是,它没有用。我将
expect(mock).toBeCalled()更改为await waitFor(() => expect(mock).toBeCalled()),但并没有什么不同。 -
对于第二个问题,建议如下:stackoverflow.com/a/68906447/17920534。效果惊人。