如何使用笑话模拟更改来测试FileReader onload? [英] How to test FileReader onload using simulate change in jest?

查看:100
本文介绍了如何使用笑话模拟更改来测试FileReader onload?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SimpleDialog.jsx

SimpleDialog.jsx

const [imagePreview, setImagePreview] = React.useState(null);

const handleChangeImage = event => {
    let reader = new FileReader();
    let file = event.target.files[0];

    reader.onload = event => {
        console.log(event);

        setImagePreview(event.target.result);
    };

    reader.readAsDataURL(file);
};

return (
    <div>
        <input
            accept="image/*"
            id="contained-button-file"
            multiple
            type="file"
            style={{ display: 'none' }}
            onChange={handleChangeImage}
        />

        <img id="preview" src={imagePreview} />
    </div>
);

SimpleDialog.test.js

SimpleDialog.test.js

it('should change image src', () => {
    const event = {
        target: {
            files: [
                {
                    name: 'image.png',
                    size: 50000,
                    type: 'image/png'
                }
            ]
        }
    };

    let spy = jest
        .spyOn(FileReader.prototype, 'onload')
        .mockImplementation(() => null);

    wrapper.find('input[type="file"]').simulate('change', event);

    expect(spy).toHaveBeenCalled();

    expect(wrapper.find('#preview').prop('src')).not.toBeNull();
});

运行测试时,出现错误 TypeError:非法调用

When running the test it gives me the error TypeError: Illegal invocation.

谁能帮助我进行单元测试?我只想模拟图像的 src 是否具有值。

Anyone who can help me with this unit test? I Just want to simulate on change if the src of an image has value or not.

推荐答案

错误的原因是 onload 被定义为属性描述符,并将其分配给 FileReader.prototype ,这是通过以下方式完成的:不支持 spyOn

The cause of the error is that onload is defined as property descriptor and assigning it to FileReader.prototype which is done by spyOn isn't supported.

没有理由模拟 onload ,因为它是在经过测试的代码中分配的,需要进行测试。

There's no reason to mock onload because it's assigned in tested code and needs to be tested.

直接的方法是不修补JSDOM FileReader 实现,但将其完全存根:

The straightforward way is to not patch JSDOM FileReader implementation but stub it entirely:

jest.spyOn(global, 'FileReader').mockImplementation(function () {
    this.readAsDataURL = jest.fn();
});

wrapper.find('input[type="file"]').simulate('change', event);


let reader = FileReader.mock.instances[0];
expect(reader.readAsDataURL).toHaveBeenCalledWith(...);
expect(reader.onload).toBe(expect.any(Function));

expect(wrapper.find('#preview').prop('src')).toBeNull();

reader.onload({ target: { result: 'foo' } });

expect(wrapper.find('#preview').prop('src')).toBe('foo');

这篇关于如何使用笑话模拟更改来测试FileReader onload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆