-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjest-wrapper.ts
More file actions
94 lines (87 loc) · 2.62 KB
/
jest-wrapper.ts
File metadata and controls
94 lines (87 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import * as assert from './ts-assert';
import { PrimaryHook, suite, Suite } from './index';
import { loadConfig } from './loadConfig';
import { customAssert } from './customAssert';
const config = loadConfig();
type Asserts = {
toEqual: (e: any) => void;
toBe: (e: any) => void;
toMatchSnapshot: () => void;
}
const createCustomMatchers = (r: any | Promise<any>): Record<string, CallableFunction> => {
if (!config.customMatchers) return {};
return Object.entries(config.customMatchers).reduce<Record<string, CallableFunction>>((pre, [key, func]) => {
return {
...pre,
[key]: () => func(r),
};
}, {});
}
export function expect(promise: Promise<any>): {
rejects: {
toThrow: (errorMessage?: string) => Promise<void>;
};
};
export function expect(any: any): Asserts;
export function expect(any: any): { not: Omit<Asserts, 'toMatchSnapshot'> };
export function expect(r: any | Promise<any>) {
const toEqual = ( e: any) => assert.equal(r, e);
return {
...createCustomMatchers(r),
not: {
toBe: (e: any) => assert.is.not(r, e),
toEqual: (e: any) => assert.not.equal(r, e),
},
toBe: (e: any) => assert.is(r, e),
toEqual: toEqual,
toStrictEqual: toEqual,
toMatchSnapshot: (_filename?: string) => {
// @ts-ignore
const filename = globalThis.CURRENT_FILE_PATH;
if (!filename) {
throw new Error('To get filename, you must pass `__filename` to first variable of toMatchSnapshot when you not use cli.');
}
// @ts-ignore
const testName = globalThis.CURRENT_TEST_NAME as string;
// @ts-ignore
const suiteNames = globalThis.CURRENT_SUITE_NAMES as string[] | undefined;
customAssert.toMatchSnapshot(r, testName, suiteNames, filename, config.snapshotResolver);
},
rejects: {
toThrow: async (errorMessage?: string) => {
try {
await (r as Promise<void>);
assert.unreachable();
} catch (e: any) {
if (typeof errorMessage === 'string') {
assert.is(e.message, errorMessage);
}
}
},
},
};
}
type HandlerProps = {
test: Suite;
expect: typeof expect;
describe: typeof describe;
afterAll: PrimaryHook;
beforeAll: PrimaryHook;
};
type Handler = (props: HandlerProps) => void;
export function describe (name: string, handler: Handler, baseSuite?: Suite) {
const test = suite(name);
if (baseSuite) {
baseSuite.nest(test);
}
handler({
test,
expect,
describe: (name: string, handler: Handler) => describe(name, handler, test),
afterAll: test.after,
beforeAll: test.before,
});
if (!baseSuite) {
test.run();
}
}