import dispatch, { init, worker } from './dispatcher-main'; jest.mock('./get-worker', () => ({ getWorker: () => ({ port: { postMessage: jest.fn(), }, }), })); describe('The dispatcher-main', () => { beforeEach(() => { init(); }); test('should create a new shared web worker', () => { expect(worker).toBeDefined(); }); test('should create a onmessage function', () => { expect(worker.port.onmessage).toBeDefined(); }); test('should return a promise if no callback is provided', () => { expect(dispatch('ping')).toBeInstanceOf(Promise); }); test('should forward the message', () => { dispatch('ping'); expect(worker.port.postMessage).toBeCalledWith({ id: 0, payload: 'ping' }); }); test('should return the response', () => { var response; const callback = (error, success) => { response = success; }; dispatch('ping', callback); worker.port.onmessage({ data: { id: 0, payload: 'pong' } }); expect(response).toEqual('pong'); }); });