-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathsharedBeforeEach.ts
51 lines (43 loc) · 1.69 KB
/
sharedBeforeEach.ts
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
import { AsyncFunc } from 'mocha';
import { takeSnapshot, SnapshotRestorer } from '@nomicfoundation/hardhat-network-helpers';
const SNAPSHOTS: Array<SnapshotRestorer> = [];
/**
* This Mocha helper acts as a `beforeEach`, but executes the initializer
* just once. It internally uses Hardhat Network and Ganache's snapshots
* and revert instead of re-executing the initializer.
*
* Note that after the last test is run, the state doesn't get reverted.
*
* @param nameOrFn A title that's included in all the hooks that this helper uses.
* @param maybeFn The initializer to be run before the tests.
*/
export function sharedBeforeEach(nameOrFn: string | AsyncFunc, maybeFn?: AsyncFunc): void {
const name = typeof nameOrFn === 'string' ? nameOrFn : undefined;
const fn = typeof nameOrFn === 'function' ? nameOrFn : (maybeFn as AsyncFunc);
let initialized = false;
beforeEach(wrapWithTitle(name, 'Running shared before each or reverting'), async function () {
if (!initialized) {
const prevSnapshot = SNAPSHOTS.pop();
if (prevSnapshot !== undefined) {
await prevSnapshot.restore();
SNAPSHOTS.push(await takeSnapshot());
}
await fn.call(this);
SNAPSHOTS.push(await takeSnapshot());
initialized = true;
} else {
const snapshot = SNAPSHOTS.pop();
if (snapshot === undefined) throw Error('Missing sharedBeforeEach snapshot');
await snapshot.restore();
SNAPSHOTS.push(await takeSnapshot());
}
});
after(async function () {
if (initialized) {
SNAPSHOTS.pop();
}
});
}
function wrapWithTitle(title: string | undefined, str: string): string {
return title === undefined ? str : `${title} at step "${str}"`;
}