简体   繁体   English

如何在反应测试库中模拟网络工作者进行测试?

[英]How to mock web worker for testing in react testing library?

I'm creating a web worker like this:我正在创建一个这样的网络工作者:

const getWebWorker = () => {
  let worker;
  if (typeof worker === 'undefined') {
    worker = new Worker('worker.js');
  }
  return worker;
};

Then I am calling the function like this:然后我这样调用函数:

useEffect(() => {
  getWebWorker().onmessage = (event) => {
    setWorkerData(event.data);
  };
}, []);

The actually worker.js file is under the public folder and postMessage's an object.实际上 worker.js 文件位于 public 文件夹下,而 postMessage 是一个对象。

I'm using the react testing library/jest to test.我正在使用 react 测试库/jest 进行测试。 When I run yarn run test I get the error ReferenceError: Worker is not defined at worker = new Worker('worker.js');当我运行yarn run test我得到错误ReferenceError: Worker is not defined at worker = new Worker('worker.js'); . .

I understand that I need to mock the worker, I'm just confused on how to.我知道我需要嘲笑工人,我只是对如何去做感到困惑。

What do I name the mock file in the __mock__ folder?我在__mock__文件夹中命名模拟文件是什么?

What would mocking the worker even look like?嘲笑工人会是什么样子?

Is there anything I have to do in the ____.test.js file? ____.test.js 文件中有什么我必须做的吗?

Thanks谢谢

Jest uses a JSDOM environment by default, which means it doesn't support Workers. Jest 默认使用 JSDOM 环境,这意味着它不支持 Workers。 This means it is impossible to test code that requires both NodeJS functionality and Web Workers.这意味着无法测试同时需要 NodeJS 功能和 Web Workers 的代码。 jsdom-worker jsdom-worker

jsdom-worker tried to bring web workers to jest, but that had no update since 2020 and seems to be unmaintained... btw there is a spin off that is marked as experimental. jsdom-worker试图让网络工作者开玩笑,但自 2020 年以来没有更新,而且似乎没有维护......顺便说一句,有一个被标记为实验性的衍生产品。

I had the same question and ended using e2e tests using playwright to test things where web workers are involved.我有同样的问题,并结束了使用playwright的 e2e 测试来测试涉及网络工作者的事物。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM