-
Notifications
You must be signed in to change notification settings - Fork 14
/
onExceptionAdvice.spec.ts
71 lines (57 loc) · 1.83 KB
/
onExceptionAdvice.spec.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { AdvicePool, IMetadata, beforeMethod, adviceMetadata, adviceParam, onException } from "../../src/kaop-ts"
describe("kaop-ts demo -> onException join point", () => {
let exceptionSpy = jest.fn()
let noopSpy = jest.fn()
let methodSpy = jest.fn()
let orderArr = []
let capturedException = null
class MyAdvicePool extends AdvicePool {
static handleException (@adviceMetadata meta: IMetadata, @adviceParam(0) order) {
orderArr.push(order)
capturedException = meta.exception
exceptionSpy()
}
static noop (@adviceParam(0) order) {
orderArr.push(order)
noopSpy()
}
}
class ExceptionTest {
@onException(MyAdvicePool.handleException)
static wrongMethod (callback: any) {
callback()
}
@beforeMethod(MyAdvicePool.noop, 0)
@onException(MyAdvicePool.handleException, 1)
@beforeMethod(MyAdvicePool.noop, 2)
static orderTest (cb: any) {
cb()
}
}
beforeEach(() => {
exceptionSpy.mockClear()
methodSpy.mockClear()
noopSpy.mockClear()
orderArr = []
})
it("throws an exception and thus calls MyAdvicePool.handleException", () => {
ExceptionTest.wrongMethod(2)
ExceptionTest.wrongMethod(methodSpy)
expect(capturedException instanceof Error).toBe(true)
expect(exceptionSpy).toHaveBeenCalledTimes(1)
expect(methodSpy).toHaveBeenCalledTimes(1)
})
it("onException must be called after the last beforeMethod, regardless of the order", () => {
ExceptionTest.orderTest(4)
expect(orderArr).toEqual([0, 2, 1])
})
it("prevents the original function from triggering twice", () => {
ExceptionTest.orderTest(() => {
methodSpy()
throw Error()
})
expect(noopSpy).toHaveBeenCalledTimes(2)
expect(exceptionSpy).toHaveBeenCalledTimes(1)
expect(methodSpy).toHaveBeenCalledTimes(1)
})
})