forked from restqa/restqa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjest.setup.js
114 lines (96 loc) · 2.62 KB
/
jest.setup.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const path = require('path')
const os = require('os')
const fs = require('fs')
const rimraf = require('rimraf')
global.JestQA = function(filename, unmount = false, debug = false) {
const DEFAULT_CONFIG = path.resolve(process.cwd(), '.restqa.yml')
const testName = path.basename(filename).replace('.test.js', '')
const tests = []
let current
const init = function() {
current = Object.seal({
id: testName + '-' + Math.floor(Math.random() * 10000000) + '-' + Date.now(),
files: [
DEFAULT_CONFIG
],
folders: [],
debug: false
})
tests.push(current)
global.console.info = jest.fn()
}
const _log = function(msg) {
(debug || current.debug) && console.log(`/JESTSQA/{ ${testName} } ->`, msg)
return true
}
const create = function(content, filename) {
_log(`creating file ${filename}`)
const folder = path.dirname(filename)
fs.mkdirSync(folder, {recursive: true})
fs.writeFileSync(filename, content)
current.files.push(filename)
_log(`File ${filename} created`)
return filename
}
const getTmpFolder = function() {
if (!current) init()
const folderName = path.resolve(os.tmpdir(), testName, current.id)
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName, {recursive: true})
}
return folderName
}
const createTmpFile = function(content, file) {
if (!current) init()
filename = path.resolve(getTmpFolder(), file)
return create(content, filename)
}
const createCwdConfig = function(content) {
if (!current) init()
return create(content, DEFAULT_CONFIG)
}
const getLoggerMock = function() {
return global.console.info
}
const clean = function() {
if (true === unmount) {
_log(`unmount mock`)
jest.resetModules()
jest.resetAllMocks()
}
current.files
.forEach(file => {
_log(`deleting file ${file}`)
fs.existsSync(file) && fs.unlinkSync(file)
})
if (fs.existsSync(getTmpFolder())) {
rimraf.sync(getTmpFolder())
}
}
const hooks = Object.seal({
beforeEach: null,
afterEach: null
})
const beforeEach = function() {
init()
_log(`Creating test ${current.id}`)
clean()
hooks.beforeEach && _log('calling hook beforeEach') && hooks.beforeEach.call(this)
}
const afterEach = function() {
if (!current) init()
clean()
hooks.afterEach && _log('calling hook afterEach') && hooks.afterEach.call(this)
current = null
}
return {
beforeEach,
afterEach,
getCurrent: () => current,
getTmpFolder,
createTmpFile,
createCwdConfig,
getLoggerMock,
hooks,
}
}