react-worker-image
react-worker-image copied to clipboard
How to mock a worker when testing with jest? Should we even test workers?
ReferenceError: Worker is not defined
Reference: https://github.com/facebook/jest/issues/3449
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
I tried but it doesn't work I am wondering should we even test external resources ?
did you guys get to close this? i am kinda stuck on the same thing
Same issue :(
Havent had time to see this but maybe this would help ? https://www.npmjs.com/package/jsdom-worker
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
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
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
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')