1 import { expect } from 'expect'
2 import { restore, stub } from 'sinon'
3 import { ClusterWorker } from '../../lib/index.js'
4 import { DEFAULT_TASK_NAME } from '../../lib/utils.js'
6 describe('Cluster worker test suite', () => {
7 const sendStub = stub().returns()
8 class SpyWorker extends ClusterWorker {
10 return { send: sendStub }
18 it('Verify that sync kill handler is called when worker is killed', () => {
19 const worker = new ClusterWorker(() => {}, {
20 killHandler: stub().returns()
23 worker.getMainWorker = stub().returns({
25 send: stub().returns()
27 worker.handleKillMessage()
28 expect(worker.getMainWorker().send.calledOnce).toBe(true)
29 expect(worker.opts.killHandler.calledOnce).toBe(true)
32 it('Verify that removeTaskFunction() is working', () => {
39 const worker = new ClusterWorker({ fn1, fn2 })
40 expect(worker.removeTaskFunction(0, fn1)).toStrictEqual({
42 error: new TypeError('name parameter is not a string')
44 expect(worker.removeTaskFunction('', fn1)).toStrictEqual({
46 error: new TypeError('name parameter is an empty string')
48 worker.getMainWorker = stub().returns({
50 send: stub().returns()
52 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toBeInstanceOf(Function)
53 expect(worker.taskFunctions.get('fn1')).toBeInstanceOf(Function)
54 expect(worker.taskFunctions.get('fn2')).toBeInstanceOf(Function)
55 expect(worker.taskFunctions.size).toBe(3)
56 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toStrictEqual(
57 worker.taskFunctions.get('fn1')
59 expect(worker.removeTaskFunction(DEFAULT_TASK_NAME)).toStrictEqual({
62 'Cannot remove the task function with the default reserved name'
65 expect(worker.removeTaskFunction('fn1')).toStrictEqual({
68 'Cannot remove the task function used as the default task function'
71 worker.removeTaskFunction('fn2')
72 expect(worker.taskFunctions.get(DEFAULT_TASK_NAME)).toBeInstanceOf(Function)
73 expect(worker.taskFunctions.get('fn1')).toBeInstanceOf(Function)
74 expect(worker.taskFunctions.get('fn2')).toBeUndefined()
75 expect(worker.taskFunctions.size).toBe(2)
76 expect(worker.getMainWorker().send.calledOnce).toBe(true)
79 it('Verify that handleError() method is working properly', () => {
80 const error = new Error('Error as an error')
81 const worker = new ClusterWorker(() => {})
82 expect(worker.handleError(error)).not.toBeInstanceOf(Error)
83 expect(worker.handleError(error)).toStrictEqual(error.message)
84 const errorMessage = 'Error as a string'
85 expect(worker.handleError(errorMessage)).toStrictEqual(errorMessage)
88 it('Verify worker invokes the getMainWorker() and send() methods', () => {
89 const worker = new SpyWorker(() => {})
90 worker.sendToMainWorker({ ok: 1 })
91 expect(worker.getMainWorker().send.calledOnce).toBe(true)