Max SchmittMS
5th February 2014

Testing Web Workers with Jasmine and gulp

For a current project I found it necessary to test a web worker with Jasmine and gulp.

var gulp = require('gulp')
var jasmine = require('gulp-jasmine')
gulp.task('default', function() {
return gulp.src('spec/test.js').pipe(jasmine())
})

The problem I had, was, that calling new Worker() gave me an error message, telling me that Worker was not defined.

I was a bit confused about this at first, but then I saw that gulp-jasmine uses minijasminenode which, if I understand correctly, essentially runs your tests and javascript using nodejs.

Web Workers using nodejs

There is no native web worker implementation in nodejs so you have to make use of a module to use the API that you're used to from modern browsers.

Luckily, there is a module called webworker-threads that makes this incredibly simple.

You can install it by simply running npm install webworker-threads --save-dev

Then, above your tests, add this line to map the global Worker-object to the module we just installed:

global.Worker = require('webworker-threads').Worker

Now you can use new Worker() without getting any error messages.

Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.