Skip to content

Commit

Permalink
refactor: refactor suite and test decorators (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastianSedzik committed Jul 10, 2023
1 parent 5b4b3a7 commit c8c9b4c
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 9 deletions.
38 changes: 32 additions & 6 deletions lib/suite.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,39 @@
import playwright from '@playwright/test';

// eslint-disable-next-line @typescript-eslint/ban-types
type Clazz = { new (...args: any[]): {} }
class SuiteDecorator {
onBeforeTestListeners: (() => void)[] = [];

/**
* Run after test.describe() and before test() calls
* @param callback
*/
onBeforeTest(callback: () => void) {
this.onBeforeTestListeners.push(callback);
}

private runOnBeforeTestListeners() {
this.onBeforeTestListeners.forEach(hook => hook());
}

run(constructor: any) {
playwright.describe(constructor.name, () => {
this.runOnBeforeTestListeners();
new constructor();
});
}
}

export type SuiteDecoratedMethod = { suiteDecorator: SuiteDecorator };

/**
* Mark class as test suite
*/
export function suite<T extends Clazz>(constructor: T) {
playwright.describe(constructor.name, () => {
new constructor();
});
export function suite<T extends { new (...args: any[]): any }>(constructor: T, context?: ClassMethodDecoratorContext) {
const suiteDecorator = new SuiteDecorator();

Object.assign(constructor, { suiteDecorator });

context?.addInitializer(() => {
suiteDecorator.run(constructor);
})
}
39 changes: 36 additions & 3 deletions lib/test.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,43 @@
import playwright from '@playwright/test';

class TestDecorator {
onBeforeTestListeners: (() => void)[] = [];

/**
* Run inside test() call, before original test code execution
* @param callback
*/
onBeforeTest(callback: () => void) {
this.onBeforeTestListeners.push(callback);
}

private runOnBeforeTestListeners() {
this.onBeforeTestListeners.forEach(hook => hook());
}

run(constructor: any, context: any) {
const constructorProxy = new Proxy(constructor, {
apply: (target: any, thisArg: any, argArray: any[]) => {
this.runOnBeforeTestListeners();
return target.apply(context, argArray);
}
})

playwright(constructor.name, constructorProxy.bind(context));
}
}

export type TestDecoratedMethod = { testDecorator: TestDecorator };

/**
* Mark class method as test
* Mark @suite class method as test
*/
export function test(originalMethod: any, context: ClassMethodDecoratorContext) {
export function test(originalMethod: any, context: ClassMemberDecoratorContext) {
const testDecorator = new TestDecorator();

Object.assign(originalMethod, { testDecorator });

context.addInitializer(function () {
playwright(originalMethod.name, originalMethod.bind(this));
testDecorator.run(originalMethod, this);
});
}

0 comments on commit c8c9b4c

Please sign in to comment.