1 import { expect } from 'expect'
2 import { restore, stub } from 'sinon'
3 import { ThreadWorker } from '../../lib/index.js'
4 import { DEFAULT_TASK_NAME } from '../../lib/utils.js'
6 describe('Thread worker test suite', () => {
7 class SpyWorker extends ThreadWorker {
10 this.port = { postMessage: stub().returns() }
18 it('Verify that sync kill handler is called when worker is killed', () => {
19 const worker = new ThreadWorker(() => {}, {
20 killHandler: stub().returns()
24 postMessage: stub().returns(),
25 unref: stub().returns(),
26 close: stub().returns()
28 worker.handleKillMessage()
29 expect(worker.port.postMessage.calledOnce).toBe(true)
30 expect(worker.port.unref.calledOnce).toBe(true)
31 expect(worker.port.close.calledOnce).toBe(true)
32 expect(worker.opts.killHandler.calledOnce).toBe(true)
35 it('Verify that removeTaskFunction() is working', () => {
42 const worker = new ThreadWorker({ fn1, fn2 })
43 expect(worker.removeTaskFunction(0, fn1)).toStrictEqual({
45 error: new TypeError('name parameter is not a string')
47 expect(worker.removeTaskFunction('', fn1)).toStrictEqual({
49 error: new TypeError('name parameter is an empty string')
52 postMessage: stub().returns()
54 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toBeInstanceOf(Function)
55 expect(worker.taskFunctions.get('fn1')).toBeInstanceOf(Function)
56 expect(worker.taskFunctions.get('fn2')).toBeInstanceOf(Function)
57 expect(worker.taskFunctions.size).toBe(3)
58 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toStrictEqual(
59 worker.taskFunctions.get('fn1')
61 expect(worker.removeTaskFunction(DEFAULT_TASK_NAME)).toStrictEqual({
64 'Cannot remove the task function with the default reserved name'
67 expect(worker.removeTaskFunction('fn1')).toStrictEqual({
70 'Cannot remove the task function used as the default task function'
73 worker.removeTaskFunction('fn2')
74 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toBeInstanceOf(Function)
75 expect(worker.taskFunctions.get('fn1')).toBeInstanceOf(Function)
76 expect(worker.taskFunctions.get('fn2')).toBeUndefined()
77 expect(worker.taskFunctions.size).toBe(2)
78 expect(worker.port.postMessage.calledOnce).toBe(true)
81 it('Verify that handleError() method is working properly', () => {
82 const error = new Error('Error as an error')
83 const worker = new ThreadWorker(() => {})
84 expect(worker.handleError(error)).toBeInstanceOf(Error)
85 expect(worker.handleError(error)).toStrictEqual(error)
86 const errorMessage = 'Error as a string'
87 expect(worker.handleError(errorMessage)).toStrictEqual(errorMessage)
90 it('Verify worker invokes the postMessage() method on port property', () => {
91 const worker = new SpyWorker(() => {})
92 worker.sendToMainWorker({ ok: 1 })
93 expect(worker.port.postMessage.calledOnce).toBe(true)