Skip to content

Commit c18c7ec

Browse files
Add test of timeout feature
1 parent e5026a6 commit c18c7ec

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

test/diff/array.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,5 +75,27 @@ describe('diff/array', function() {
7575
{count: 1, value: [d], removed: undefined, added: true}
7676
]);
7777
});
78+
it('Should terminate early if execution time exceeds `timeout` ms', function() {
79+
// To test this, we also pass a comparator that hot sleeps as a way to
80+
// artificially slow down execution so we reach the timeout.
81+
function comparator(left, right) {
82+
const start = Date.now();
83+
// Hot-sleep for 10ms
84+
while (Date.now() < start + 10) {
85+
// Do nothing
86+
}
87+
return left === right;
88+
}
89+
90+
// It will require 14 comparisons (140ms) to diff these arrays:
91+
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
92+
const arr2 = ['a', 'b', 'c', 'd', 'x', 'y', 'z'];
93+
94+
// So with a timeout of 50ms, we are guaranteed failure:
95+
expect(diffArrays(arr1, arr2, {comparator, timeout: 50})).to.be.undefined;
96+
97+
// But with a longer timeout, we expect success:
98+
expect(diffArrays(arr1, arr2, {comparator, timeout: 1000})).not.to.be.undefined;
99+
});
78100
});
79101
});

0 commit comments

Comments
 (0)