Merge pull request #59 from pioardi/dependabot/npm_and_yarn/mocha-8.2.1
[poolifier.git] / tests / dynamic.test.js
CommitLineData
506c2a14 1const expect = require('expect')
2const DynamicThreadPool = require('../lib/dynamic')
3const min = 1
c719859c 4const max = 3
506c2a14 5const pool = new DynamicThreadPool(min, max,
106744f7 6 './tests/workers/testWorker.js',
506c2a14 7 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
8
9describe('Dynamic thread pool test suite ', () => {
10 it('Verify that the function is executed in a worker thread', async () => {
11 const result = await pool.execute({ test: 'test' })
12 expect(result).toBeDefined()
13 expect(result).toBeFalsy()
14 })
15
16 it('Verify that new workers are created when required, max size is not exceeded and that after a while new workers will die', async () => {
17 const promises = []
18 let closedThreads = 0
b755d5be 19 let fullPool = 0
20 pool.emitter.on('FullPool', () => fullPool++)
c719859c 21 for (let i = 0; i < (max * 2); i++) {
506c2a14 22 promises.push(pool.execute({ test: 'test' }))
23 }
24 expect(pool.workers.length).toBe(max)
25 pool.workers.forEach(w => {
26 w.on('exit', () => {
27 closedThreads++
28 })
29 })
b755d5be 30 expect(fullPool > 1).toBeTruthy()
c719859c 31 await new Promise(resolve => setTimeout(resolve, 2000))
506c2a14 32 expect(closedThreads).toBe(max - min)
33 })
34
35 it('Shutdown test', async () => {
36 let closedThreads = 0
37 pool.workers.forEach(w => {
38 w.on('exit', () => {
39 closedThreads++
40 })
41 })
1f9a5a44 42 await pool.destroy()
506c2a14 43 expect(closedThreads).toBe(min)
44 })
45
46 it('Validations test', () => {
47 let error
48 try {
49 const pool1 = new DynamicThreadPool()
50 console.log(pool1)
51 } catch (e) {
52 error = e
53 }
54 expect(error).toBeTruthy()
55 expect(error.message).toBeTruthy()
56 })
57
58 it('Should work even without opts in input', async () => {
106744f7 59 const pool1 = new DynamicThreadPool(1, 1, './tests/workers/testWorker.js')
506c2a14 60 const res = await pool1.execute({ test: 'test' })
61 expect(res).toBeFalsy()
62 })
63})