react-worker-image icon indicating copy to clipboard operation
react-worker-image copied to clipboard

How to mock a worker when testing with jest? Should we even test workers?

Open manjula-dube opened this issue 7 years ago • 10 comments

ReferenceError: Worker is not defined

manjula-dube avatar Feb 10 '18 06:02 manjula-dube

Reference: https://github.com/facebook/jest/issues/3449

manjula-dube avatar Feb 10 '18 06:02 manjula-dube

wondering if setting a mock worker class would work

  class Worker {
    constructor(stringUrl) {
      this.url = stringUrl;
      this.onmessage = () => {};
    }

    postMessage(msg) {
      this.onmessage(msg);
    }
  }

and then doing

window.Worker = Worker

nitish24p avatar Feb 10 '18 07:02 nitish24p

I tried but it doesn't work I am wondering should we even test external resources ?

manjula-dube avatar Feb 10 '18 08:02 manjula-dube

did you guys get to close this? i am kinda stuck on the same thing

prateekbh avatar Jan 06 '19 14:01 prateekbh

Same issue :(

hayait599 avatar Apr 22 '19 06:04 hayait599

Havent had time to see this but maybe this would help ? https://www.npmjs.com/package/jsdom-worker

nitish24p avatar Apr 23 '19 08:04 nitish24p

Havent had time to see this but maybe this would help ? https://www.npmjs.com/package/jsdom-worker

Thanks, the package actually works. It produces some error message though, even when all tests pass. It doesn't look like it's maintained any longer unfortunately

andreasjhagen avatar Jul 17 '19 21:07 andreasjhagen

For people like me, that want to keep the console clean and want to get rid of the error message after successfull tests, I created a fork and fixed it:

https://www.npmjs.com/package/jsdom-worker-fix

andreasjhagen avatar Jul 23 '19 18:07 andreasjhagen

For people like me, that want to keep the console clean and want to get rid of the error message after successfull tests, I created a fork and fixed it:

https://www.npmjs.com/package/jsdom-worker-fix

@andreasjhagen can u show implementation in create-react-app, if possible

ghost avatar May 12 '20 06:05 ghost

If your working with Shared Workers this is what has worked for me. First, you create a mock folder like this :

├── src
│     ├── workers
│        ├── __mocks__
│        │   └── myworker.worker.js
│        └── myworker.worker.js

And then you can add a mock for your worker like this:

class SharedWorker {
  constructor(stringUrl) {
    this.url = stringUrl;
    this.onconnect = () => {};
    this.port = {
      start: () => {},
      postMessage: () => {},
      onmessage: () => {},
    };
  }
}

export default SharedWorker;

finally, in your tests that require your worker, you can do this:

jest.mock('./path-to-your-worker')

ViniciusResende avatar Jul 06 '21 11:07 ViniciusResende