October 05, 2017
TestsSource
- web worker
- SharedArrayBuffer
Source Code
The source code we wrote during the event.
spec.js
// the tests below do NOT run in nodejs as given, in the browser (maybe)
xdescribe('web worker', function() {
it('gets and returns a modified message', function(done) {
const response = "self.onmessage=(e)=>postMessage('from worker' + e.data)";
const worker = new Worker('data:application/javascript,' +
encodeURIComponent(response) );
worker.postMessage('test');
worker.onmessage = function(e) {
assert.equal(e.data, 'from workertest');
done();
};
});
it('passing a function throws', () => {
const fn = () => {
const response = "self.onmessage=(e)=>postMessage('from worker' + e.data)";
const worker = new Worker('data:application/javascript,' +
encodeURIComponent(response) );
worker.postMessage(() => {});
}
assert.throws(fn);
});
it('passing an object stringifies it', (done) => {
const response = "self.onmessage=(e)=>postMessage(e.data)";
const worker = new Worker('data:application/javascript,' +
encodeURIComponent(response) );
worker.postMessage({});
worker.onmessage = function(e) {
assert.deepEqual(e.data, {});
done();
};
});
});
xdescribe('SharedArrayBuffer', () => {
it('pass a shared array buffer and read it`s content back', (done) => {
const buf = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
const sharedArray = new Int32Array(buf);
const response = "self.onmessage=(e)=>{"+
"const sharedArray = new Int32Array(e.data);"+
"postMessage(sharedArray);"+
"}"
;
const worker = new Worker('data:application/javascript,' +
encodeURIComponent(response) );
worker.postMessage(buf);
worker.onmessage = function(e) {
assert.deepEqual(e.data, sharedArray);
done();
}
});
it('pass a shared array buffer, modify it and read it`s content', (done) => {
const buf = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
const sharedArray = new Int32Array(buf);
const response = "self.onmessage=(e)=>{"+
"const sharedArray = new Int32Array(e.data);"+
"sharedArray[0] = 42;"+
"postMessage('');"+
"}"
;
const worker = new Worker('data:application/javascript,' +
encodeURIComponent(response) );
worker.postMessage(buf);
worker.onmessage = function(e) {
assert.equal(sharedArray[0], 42);
done();
}
});
it('pass a shared array buffer, modify it in the main thread, return in the worker and read it`s content back', (done) => {
const buf = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
const sharedArray = new Int32Array(buf);
const response = "self.onmessage=(e)=>{"+
"const sharedArray = new Int32Array(e.data);"+
"postMessage(e.data);"+
"}"
;
const worker = new Worker('data:application/javascript,' +
encodeURIComponent(response) );
worker.postMessage(buf.toString());
setTimeout(()=>{sharedArray[0] = 42;}, 1)
worker.onmessage = function(e) {
assert.deepEqual(e.data, buf);
done();
}
console.log(buf);
});
});