Currently I have these tests, built with Jest and MSW version 1. Migrating to MSW version 2 creates a warning in the console with node18 and react app.
it('requests endpoint with a file as formdata', async () => {
server.use(
http.post('/endpoint', async ({ request }) => {
requests.push(request);
return HttpResponse.json({ data: 'some data' });
}),
);
const file = new File(
[fs.readFileSync(path.join(__dirname, '__fixtures__', 'file.png'))],
'file.png',
);
const body = new FormData();
body.append('file', file);
// internal functionality
await expect(postToBackend({
endpoint: '/endpoint',
body,
})).resolves.toEqual({ data: 'some data' });
body.delete('file');
expect(requests).toHaveLength(1);
});
but also this
it('requests endpoint with a string as formdata', async () => {
server.use(
http.post('/endpoint', async ({ request }) => {
requests.push(request);
return HttpResponse.json({ data: 'some data' });
}),
);
const body = new FormData();
body.append('file', 'some form data');
// internal functionality
await expect(postToBackend({
endpoint: '/endpoint',
body,
})).resolves.toEqual({ data: 'some data' });
body.delete('file');
expect(requests).toHaveLength(1);
});
This code:
await expect(postToBackend({ endpoint: '/endpoint', body}))
.resolves
.toEqual({ data: 'some data' });
gives this warning message:
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with
--detectOpenHandlesto find leaks. Active timers can also cause this, ensure that.unref()was called on them.
This warning message seems to appear only if body is of the FormData() type, with a file or a string as content, it doesn't matter.
No warning message if body is a string or an object.
Ideas on how to remove warnings from these unit tests?
If you're willing to drop the FormData function in NodeJS and use a bodyParser. You can use the express app framework in NodeJS and a Content-Type www-x-urlencoded-form header on your xmlhttprequests to send the data to NodeJS.
and on your client use: