Skip to content

Commit

Permalink
Change Worker from inherit to member (#2)
Browse files Browse the repository at this point in the history
* Change Worker from inherit to member

* Add tests
  • Loading branch information
SuperSodaSea authored Feb 18, 2024
1 parent e122e5f commit e47333b
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ export function buildWorkerCode(source: string, moduleType: ModuleType)
let result = `\
const WORKER_CODE = ${JSON.stringify(source)};
let WORKER_URL = null;
class WorkerInstance extends Worker
class WorkerInstance
{
constructor()
{
if (!WORKER_URL)
{
WORKER_URL = URL.createObjectURL(new Blob([WORKER_CODE], { type: 'application/javascript' }));
}
super(WORKER_URL);
this.worker = new Worker(WORKER_URL);
}
}
WorkerInstance.revokeObjectURL = function revokeObjectURL()
Expand Down
6 changes: 3 additions & 3 deletions test/JestTransform.tests.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import AdderWorker from 'worker:./workers/Adder.worker.ts';

describe('Test', () =>
describe('JestTransform', () =>
{
it('should work', async () =>
new Promise<void>((resolve) =>
{
const worker = new AdderWorker();

worker.onmessage = (event) =>
worker.worker.onmessage = (event) =>
{
expect(event.data).toBe(2);
resolve();
};

worker.postMessage({ a: 1, b: 1 });
worker.worker.postMessage({ a: 1, b: 1 });
})
);
});
23 changes: 23 additions & 0 deletions test/NoWorker.tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import AdderWorker from 'worker:./workers/Adder.worker.ts';

describe('NoWorker', () =>
{
let savedWorker: typeof Worker;

beforeAll(() =>
{
savedWorker = globalThis.Worker;
// @ts-expect-error: remove Worker
delete globalThis.Worker;
});
afterAll(() =>
{
globalThis.Worker = savedWorker;
});

it('should throw if no Worker', () =>
{
expect(() => new AdderWorker()).toThrow(ReferenceError);
}
);
});
4 changes: 3 additions & 1 deletion test/global.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
declare module '*.worker.ts'
{
class WorkerInstance extends Worker
class WorkerInstance
{
public worker: Worker;

constructor();

static revokeObjectURL(): void;
Expand Down

0 comments on commit e47333b

Please sign in to comment.