-
Notifications
You must be signed in to change notification settings - Fork 0
/
jest.helper.mts
72 lines (64 loc) · 2.12 KB
/
jest.helper.mts
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
/* eslint-disable import/no-extraneous-dependencies */
import type { IDesensitizer } from '@guanghechen/helper-jest'
import {
composeStringDesensitizers,
createFilepathDesensitizer,
createJsonDesensitizer,
} from '@guanghechen/helper-jest'
import fs from 'node:fs'
import path from 'node:path'
import url from 'node:url'
export { isCI } from 'ci-info'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
export const workspaceRootDir = __dirname
/**
* Desensitize test data.
*/
export const desensitize: IDesensitizer<any> & IDesensitizer<string> = createJsonDesensitizer({
string: composeStringDesensitizers(
createFilepathDesensitizer(workspaceRootDir, '<$WORKSPACE$>'),
text => text.replace(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/, '<$Date$>'),
text => text.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/, '<$ISO-Date$>'),
),
}) as IDesensitizer<any>
/**
* Locate fixture filepath.
* @param p
* @returns
*/
export const locateFixtures = (...p: string[]): string => {
const relativePackagePath: string = path
.relative(workspaceRootDir, path.resolve())
.split(path.sep)
.slice(0, 2)
.join(path.sep)
const testRootDior: string = path.resolve(workspaceRootDir, relativePackagePath)
return path.resolve(testRootDior, '__test__/fixtures', ...p)
}
/**
* Load fixture filepath.
* @param p
* @returns
*/
export const loadFixtures = (...p: string[]): string =>
fs.readFileSync(locateFixtures(...p), 'utf-8')
/**
* Remove filepaths
* @param filepaths
*/
export const unlinkSync = (...filepaths: Array<string | null | undefined | string[]>): void => {
for (let filepath of filepaths) {
if (filepath == null) continue
if (!Array.isArray(filepath)) filepath = [filepath]
for (const p of filepath) if (fs.existsSync(p)) fs.unlinkSync(p)
}
}
export const assertPromiseThrow = async (
fn: () => Promise<unknown>,
errorPattern: string | RegExp,
): Promise<void> => {
await expect(() => fn()).rejects.toThrow(errorPattern)
}
export const assertPromiseNotThrow = async (fn: () => Promise<unknown>): Promise<void> => {
await expect(fn().then(() => {})).resolves.toBeUndefined()
}