1 | 'use strict'
|
2 |
|
3 | import sinon from 'sinon'
|
4 | import engineFactory from '../src/index'
|
5 |
|
6 | async function factSenior (params, engine) {
|
7 | return 65
|
8 | }
|
9 |
|
10 | async function factChild (params, engine) {
|
11 | return 10
|
12 | }
|
13 |
|
14 | async function factAdult (params, engine) {
|
15 | return 30
|
16 | }
|
17 |
|
18 | describe('Engine: "all" conditions', () => {
|
19 | let engine
|
20 |
|
21 | describe('supports a single "all" condition', () => {
|
22 | let event = {
|
23 | type: 'ageTrigger',
|
24 | params: {
|
25 | demographic: 'under50'
|
26 | }
|
27 | }
|
28 | let conditions = {
|
29 | all: [{
|
30 | 'fact': 'age',
|
31 | 'operator': 'lessThan',
|
32 | 'value': 50
|
33 | }]
|
34 | }
|
35 | let eventSpy = sinon.spy()
|
36 | beforeEach(() => {
|
37 | eventSpy.reset()
|
38 | let rule = factories.rule({ conditions, event })
|
39 | engine = engineFactory()
|
40 | engine.addRule(rule)
|
41 | engine.on('success', eventSpy)
|
42 | })
|
43 |
|
44 | it('emits when the condition is met', async () => {
|
45 | engine.addFact('age', factChild)
|
46 | await engine.run()
|
47 | expect(eventSpy).to.have.been.calledWith(event)
|
48 | })
|
49 |
|
50 | it('does not emit when the condition fails', () => {
|
51 | engine.addFact('age', factSenior)
|
52 | engine.run()
|
53 | expect(eventSpy).to.not.have.been.calledWith(event)
|
54 | })
|
55 | })
|
56 |
|
57 | describe('supports "any" with multiple conditions', () => {
|
58 | let conditions = {
|
59 | all: [{
|
60 | 'fact': 'age',
|
61 | 'operator': 'lessThan',
|
62 | 'value': 50
|
63 | }, {
|
64 | 'fact': 'age',
|
65 | 'operator': 'greaterThan',
|
66 | 'value': 21
|
67 | }]
|
68 | }
|
69 | let event = {
|
70 | type: 'ageTrigger',
|
71 | params: {
|
72 | demographic: 'adult'
|
73 | }
|
74 | }
|
75 | let eventSpy = sinon.spy()
|
76 | beforeEach(() => {
|
77 | eventSpy.reset()
|
78 | let rule = factories.rule({ conditions, event })
|
79 | engine = engineFactory()
|
80 | engine.addRule(rule)
|
81 | engine.on('success', eventSpy)
|
82 | })
|
83 |
|
84 | it('emits an event when every condition is met', async () => {
|
85 | engine.addFact('age', factAdult)
|
86 | await engine.run()
|
87 | expect(eventSpy).to.have.been.calledWith(event)
|
88 | })
|
89 |
|
90 | describe('a condition fails', () => {
|
91 | it('does not emit when the first condition fails', async () => {
|
92 | engine.addFact('age', factChild)
|
93 | await engine.run()
|
94 | expect(eventSpy).to.not.have.been.calledWith(event)
|
95 | })
|
96 |
|
97 | it('does not emit when the second condition', async () => {
|
98 | engine.addFact('age', factSenior)
|
99 | await engine.run()
|
100 | expect(eventSpy).to.not.have.been.calledWith(event)
|
101 | })
|
102 | })
|
103 | })
|
104 | })
|