Jest.js 如何删除从FormData主体请求的单元测试中泄漏的警告?

ggazkfy8  于 9个月前  发布在  Jest
关注(0)|答案(1)|浏览(133)

目前我有这些测试,用Jest和MSW版本1构建。迁移到MSW版本2会在控制台中用node18和react应用程序创建一个警告。

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);
});

字符串
也是这个

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);
});


此代码:

await expect(postToBackend({ endpoint: '/endpoint', body}))
  .resolves
  .toEqual({ data: 'some data' });


给出此警告消息:
工作进程无法正常退出,并已强制退出。这可能是由于不正确的拆除导致测试泄漏。请尝试使用--detectOpenHandles运行以查找泄漏。活动计时器也可能导致此问题,请确保在其上调用.unref()
这个warning消息似乎只在bodyFormData()类型时出现,内容是文件还是字符串都无所谓。如果body是字符串或对象,则没有warning消息。
如何从这些单元测试中删除警告?

ffvjumwh

ffvjumwh1#

如果你愿意放弃NodeJS中的FormData函数而使用bodyParser,你可以在NodeJS中使用express app框架,在xmlhttprequests上使用Content-Type www-x-urlencoded-form header来将数据发送到NodeJS。

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

字符串
在您的客户端上用途:

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");

相关问题