0

I have a mock service worker (MSW), which intercepts any axios rest api request and mocks it.

I have one specific api request to upload a file, it also has progress event, which tell me about the progress of the file being uploaded.

apiClient.doPut(
    `/uploadFile/files`,
    formData,
    {
        timeout: 35000,
        headers: {
            "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (progressEvent) => {
            const progress: number = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
            );
            console.log("progress");
            setProgressMap((prev) => new Map(prev.set(fileName, progress)));
        },
    }).then((res) => {
        console.log("Here");
        return res.data;
    }).catch((error) => {
        console.log("error);
    });

This code works fine. but when I run the testcases, MSW is unable to intercept this request and the catch block gets executed.

When I remove the onUploadProgress from the configuration MSW is able to mock the request correctly.

How can I test or mock the onUploadProgress for this particular API using MSW, Jest or React testing library?

1 Answers1

1

I have two suspicions about why this may be happening. The first one, is that you're using an old version of MSW and its @mswjs/interceptors dependency, in particular. So one thing to do on your side is to ensure you're using the latest version from NPM, which you can do by npm install msw@latest.

The other suspicion is related to some of the changes we did to the Interceptors library that handles request interception in Node.js, where you experience the issue. Axios implements upload progress indication using XMLHttpRequest and its progress event. We've done a lot of improvements around XHR interception and mocking but not all of them are currently present on the latest version of MSW.

In general, I highly recommend you try using msw@next, which is a breaking release that contains the most up-to-date bug fixes and functionality improvements of the library. You can learn more about it in this GitHub discussion. I am fairly confident onUploadProgress works correctly with that release.

Bear in mind, msw@next is a breaking release. There is quite a number of things necessary to do to migrate to it. Those things include updating to Node.js 18 or newer, for example. Keep this in mind in regards to your time availability when considering my suggestion.

kettanaito
  • 974
  • 5
  • 12