1 import { expect } from 'expect'
2 import { restore, stub } from 'sinon'
3 import { ThreadWorker } from '../../lib/index.cjs'
4 import { DEFAULT_TASK_NAME } from '../../lib/utils.cjs'
6 describe('Thread worker test suite', () => {
11 it('Verify that sync kill handler is called when worker is killed', () => {
12 const worker = new ThreadWorker(() => {}, {
13 killHandler: stub().returns()
17 postMessage: stub().returns(),
18 unref: stub().returns(),
19 close: stub().returns()
21 worker.handleKillMessage()
22 expect(worker.port.postMessage.calledOnce).toBe(true)
23 expect(worker.port.unref.calledOnce).toBe(true)
24 expect(worker.port.close.calledOnce).toBe(true)
25 expect(worker.opts.killHandler.calledOnce).toBe(true)
28 it('Verify that removeTaskFunction() is working', () => {
35 const worker = new ThreadWorker({ fn1, fn2 })
37 postMessage: stub().returns()
39 expect(worker.removeTaskFunction(0, fn1)).toStrictEqual({
41 error: new TypeError('name parameter is not a string')
43 expect(worker.removeTaskFunction('', fn1)).toStrictEqual({
45 error: new TypeError('name parameter is an empty string')
47 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toBeInstanceOf(Function)
48 expect(worker.taskFunctions.get('fn1')).toBeInstanceOf(Function)
49 expect(worker.taskFunctions.get('fn2')).toBeInstanceOf(Function)
50 expect(worker.taskFunctions.size).toBe(3)
51 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toStrictEqual(
52 worker.taskFunctions.get('fn1')
54 expect(worker.removeTaskFunction(DEFAULT_TASK_NAME)).toStrictEqual({
57 'Cannot remove the task function with the default reserved name'
60 expect(worker.removeTaskFunction('fn1')).toStrictEqual({
63 'Cannot remove the task function used as the default task function'
66 worker.removeTaskFunction('fn2')
67 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toBeInstanceOf(Function)
68 expect(worker.taskFunctions.get('fn1')).toBeInstanceOf(Function)
69 expect(worker.taskFunctions.get('fn2')).toBeUndefined()
70 expect(worker.taskFunctions.size).toBe(2)
71 expect(worker.port.postMessage.calledOnce).toBe(true)
74 it('Verify that handleError() method is working properly', () => {
75 const error = new Error('Error as an error')
76 const worker = new ThreadWorker(() => {})
77 expect(worker.handleError(error)).toBeInstanceOf(Error)
78 expect(worker.handleError(error)).toStrictEqual(error)
79 const errorMessage = 'Error as a string'
80 expect(worker.handleError(errorMessage)).toStrictEqual(errorMessage)
83 it('Verify that sendToMainWorker() method invokes the port property postMessage() method', () => {
84 const worker = new ThreadWorker(() => {})
85 worker.port = { postMessage: stub().returns() }
86 worker.sendToMainWorker({ ok: 1 })
87 expect(worker.port.postMessage.calledOnce).toBe(true)