How to remove warning leaking from unit tests that requests with FormData body?

189 Views Asked by At

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 --detectOpenHandles to 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?

2

There are 2 best solutions below

0
On

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.

var express = require('express');
var app = express();
var server = require('http').Server(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); 

and on your client use:

    function z(url, data, async){
        xml = new XMLHttpRequest();
        xml.open("POST", url, !(!async));
        xml.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xml.send(data);
        return xml.responseText;
    }
    z("endpoint", "data=string");
1
On

I encountered the same situation and opened an issue on the msw repository : https://github.com/mswjs/msw/issues/2078.

It seems to be a bug with msw 2.