Skip to content

Commit

Permalink
WIP: cancellable decorator and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
CMCDragonkai committed Sep 5, 2022
1 parent 864db7c commit f88b157
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions tests/contexts/decorators/cancellable.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { ContextCancellable } from '@/contexts/types';
import { PromiseCancellable } from '@matrixai/async-cancellable';
import context from '@/contexts/decorators/context';
import cancellable from '@/contexts/decorators/cancellable';
import { AsyncFunction } from '@/utils';

describe('context/decorators/cancellable', () => {
describe('cancellable decorator runtime validation', () => {
Expand Down Expand Up @@ -29,4 +31,65 @@ describe('context/decorators/cancellable', () => {
}).rejects.toThrow(TypeError);
});
});
describe('cancellable decorator syntax', () => {
// Decorators cannot change type signatures
// use overloading to change required context parameter to optional context parameter
const symbolFunction = Symbol('sym');
class X {
functionPromise(
ctx?: Partial<ContextCancellable>,
): PromiseCancellable<void>;
@cancellable()
functionPromise(
@context ctx: ContextCancellable,
): Promise<void> {
expect(ctx.signal).toBeInstanceOf(AbortSignal);
return new Promise((resolve) => void resolve());
}

asyncFunction(
ctx?: Partial<ContextCancellable>,
): PromiseCancellable<void>;
@cancellable(true)
async asyncFunction(
@context ctx: ContextCancellable,
): Promise<void> {
expect(ctx.signal).toBeInstanceOf(AbortSignal);
}

[symbolFunction](
ctx?: Partial<ContextCancellable>,
): PromiseCancellable<void>;
@cancellable(false)
[symbolFunction](
@context ctx: ContextCancellable,
): Promise<void> {
expect(ctx.signal).toBeInstanceOf(AbortSignal);
return new Promise((resolve) => void resolve());
}
}
const x = new X();
test('functionPromise', async () => {
await x.functionPromise();
await x.functionPromise({});
await x.functionPromise({ signal: (new AbortController()).signal });
expect(x.functionPromise).toBeInstanceOf(Function);
expect(x.functionPromise.name).toBe('functionPromise');
});
test('asyncFunction', async () => {
await x.asyncFunction();
await x.asyncFunction({});
await x.asyncFunction({ signal: (new AbortController()).signal });
expect(x.asyncFunction).toBeInstanceOf(Function);
expect(x.asyncFunction).not.toBeInstanceOf(AsyncFunction);
expect(x.asyncFunction.name).toBe('asyncFunction');
});
test('symbolFunction', async () => {
await x[symbolFunction]();
await x[symbolFunction]({});
await x[symbolFunction]({ signal: (new AbortController()).signal });
expect(x[symbolFunction]).toBeInstanceOf(Function);
expect(x[symbolFunction].name).toBe('[sym]');
});
});
});

0 comments on commit f88b157

Please sign in to comment.