nitish24p / react-worker-image

React component to fetch image resources via web workers 🤖🤖
MIT License
232 stars 18 forks source link

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

Open manjula-dube opened 6 years ago

manjula-dube commented 6 years ago

ReferenceError: Worker is not defined

manjula-dube commented 6 years ago

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

nitish24p commented 6 years ago

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
manjula-dube commented 6 years ago

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

prateekbh commented 5 years ago

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

hayait599 commented 5 years ago

Same issue :(

nitish24p commented 5 years ago

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

andreasjhagen commented 5 years ago

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 commented 5 years ago

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

ghost commented 4 years ago

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

ViniciusResende commented 3 years ago

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')