-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (51 loc) · 1.49 KB
/
index.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
class UnexpectedConsoleOutputError extends Error{
constructor(message, consoleMessages){
super(`${message}: ${JSON.stringify(consoleMessages, null, 2)}`)
this.consoleMessages = consoleMessages
}
}
const defaultConfig = {
onError: ({consoleMessages}) => {
if(consoleMessages.length > 0){
throw new UnexpectedConsoleOutputError('Unhandled console messages in test', consoleMessages)
}
},
filterEntries: consoleEntry => consoleEntry,
}
function errorOnConsoleOutput(
{
onError = defaultConfig.onError,
filterEntries = defaultConfig.filterEntries,
} = {}
){
let consoleMessages = []
const flushConsoleMessages = () => {
const consoleMessagesToTake = consoleMessages
consoleMessages = []
return consoleMessagesToTake
}
beforeEach(() => {
Object.keys(global.console)
.filter(consoleFnName => {
return consoleFnName.charAt(0) !== '_' && typeof(global.console[consoleFnName]) === 'function'
})
.forEach(consoleFnName => {
global.console[consoleFnName] = (...args) => {
const consoleEntry = {level: consoleFnName, args};
if (filterEntries(consoleEntry)) {
consoleMessages.push(consoleEntry)
}
}
})
})
afterEach(() => {
const flushedConsoleMessages = flushConsoleMessages();
onError({consoleMessages: flushedConsoleMessages})
})
return flushConsoleMessages
}
module.exports = {
UnexpectedConsoleOutputError,
defaultConfig,
errorOnConsoleOutput
}