Jest: Worker is not defined

Created on 3 May 2017  路  7Comments  路  Source: facebook/jest

Do you want to request a feature or report a bug?
A bug.

What is the current behavior?
When trying to test a web worker, the Worker constructor is throwing an error saying it is undefined.
Here is an example: https://repl.it/HdhL/0

What is the expected behavior?
The Worker constructor creates a new Web Worker.

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

Jest Config:

"jest": {
    "globals": {
      "window": true
    },
    "testResultsProcessor": "./node_modules/jest-junit",
    "moduleFileExtensions": [
      "js"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|scss|html)$": "identity-obj-proxy"
    }
  }

Jest Version: 19.0.2
Yarn: 0.23.2
Windows 10 (w/ Creators Update)

Most helpful comment

If anyone else is looking for a Worker stub here is one I made. I haven't had any issues with it yet.

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

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

If you are using create-react-app you can stub workers globally by adding this to src/setupTests.js.
window.Worker = Worker;

All 7 comments

You'll need to create your own mock for web workers. This is an unsupported feature and should either be part of your own mocks or part of jsdom, but not Jest. Feel free to make a mock and put it on npm for other people to use as well :)

Thanks @cpojer! Wasn't entirely sure. Thanks again for the advice. :)

Sorry to comment on a closed issue, but I'm having the same problem, and can't find another way of contacting you @patoncrispy...
Did you managed to work this out? Feel free to answer me by email!

Hey @israelss! I just extracted as much of my code from the worker into a separate module and tested that. I want to write my own mocks for a web worker, but a bit busy at the moment.

Thanks for reply @patoncrispy, and sorry for late response!
I was able to mock the module that uses window.Worker, but not the Worker itself. I'll leave it that way for now.
Thanks again!

setting window.Worker = someClass should do the trick

If anyone else is looking for a Worker stub here is one I made. I haven't had any issues with it yet.

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

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

If you are using create-react-app you can stub workers globally by adding this to src/setupTests.js.
window.Worker = Worker;

Was this page helpful?
0 / 5 - 0 ratings