JEST Unit test browser-image-compression

Viewed 12

I'm doing a unit test with jest in react (react-testing-library) I am simulating that the user clicked on the input file and created a new file of type image/png. So far I have no problems but when I get to the part where the file is compressed (using the browser-image-compression library) I get the following error

const img = window._document.createElement("img");

TypeError: Cannot read properties of undefined (reading 'createElement')

My code:

let base64img  = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
beforeEach(() => {
    const readAsDataURL = jest.fn();
    jest.spyOn(global, "FileReader")
        .mockImplementation(function () {
            this.readAsDataURL = readAsDataURL;
            this.result = base64img
        });
    
});

  test("input type file", async () => {

    let setIsOpen = jest.fn()

    let user = {
        fullName: "Test",
        email: "test@test.com",
        accessToken: "12345",
        avatar: ""
    }
    const mockId = "userData";
    const mockJson = JSON.stringify(user);
    window.localStorage.setItem(mockId, mockJson);

    let container
    await act(async () => {
        container = render(
            <Router>
                <Provider store={store}>
                    <ModalChangePhoto isOpen={true} setIsOpen={setIsOpen} />
                </Provider>
            </Router>
        )
    })


    const inputFileNode = container.getByLabelText("inputFileAvatar")
  
    let reader = FileReader.mock.instances[0];

    const file = new File(['hello'], 'hello.png', {type: 'image/png'})

    await act(async () => {
        await waitFor(() => {
            userEvent.upload(inputFileNode, file);
        });
    });

    await act(async () => {
        await waitFor(() => {
            reader = FileReader.mock.instances[0];
        });
    });

    await act(async () => {
        if (reader) {
            reader.onload({ target: { files: [file] } });
        }
    });


})

and the part where it marks the error is when doing the next

 import imageCompression from 'browser-image-compression'
 const options = {
        maxSizeMB: 1,
        initialQuality: 0.6,
        maxWidthOrHeight: 1080
    }
  let resultCompress = await imageCompression(file, options)

Could someone help me to solve the problem?

0 Answers
Related