Continuing with this month's theme, Time, I want to share a strategy I've used in the past when I've needed to write unit tests for logic that depends on time, timers, timeouts, etc.
Take for example a cache where items can expire. Suppose you want items to be evicted once they have gone untouched for some period of time.
One simple approach might be to take the idle expiry as a parameter. Say 20 minutes in a production build and only 100 milliseconds during testing.
Testing this way can lead to brittle tests. By brittle I mean that your tests will pass most of the time. But occasionally, if your machine is busy or the tests run on a different machine, it's possible that you'll get some false negatives.
In addition, your tests will take longer to run than necessary.
Here's what I do instead.
Last week I wrote about Using a Timer in a React Component but only gave a simple example. This week I'm going to review some code with more complexity.
A question came up on Reddit recently where someone was having difficulty creating a visual bubble sort in React. The posted code has a few problems. Take a look to see if you can spot any.
bubbleSort() { const arr = this.state.array; const n = arr.length; for (let i = n - 1; i > 0; i--) { for (let j = 0; j < i; j++) { setTimeout(() => { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; this.setState({ swaps: this.state.swaps + 1 }); } this.setState({ comparisons: this.state.comparisons + 1 }); }, i * 10); } } this.setState({ array: arr });}
Sometimes you might need to write a component that relies on time. Perhaps you need to change some state after a period of time. Or maybe you need to perform a change that repeats on a regular interval.
Adding time-based changes to your React components is easy to perform in stateless functional components using a few React hooks. I'm going to show you how.
I stumbled across a new type definition today -- at least it was new to me -- and I was so excited because I'd been using a less-than-perfect alternative for so long.
Before I go on, I should clarify what I mean by a keyed collection. Different languages call it by different names. In JavaScript/TypeScript it's just an object
since object is so versatile. (Okay, technically there is a Map in JavaScript too but it has a different interface). In C# it's called a Dictionary.
Some people might call it a lookup or a map.