I am trying to develop some code for my own library. I chose Jest as the testing framework. What I would like to do is have test cases to make sure that a particular function is not taking too much time to execute. Basically that requires some way of timing how much time a function call is taking. I am aware of the standard ways of measuring time. However, it may be nice to have some way of letting Jest do that work. I have tried looking into the (open and closed) issues on the Github Jest repo but I couldn't find anything that addresses my question in particular. Does anyone know of such a way of timing function calls with Jest?
Asked
Active
Viewed 1,969 times
3
-
I don't think Jest has a way to benchmark your code. Here I found a discussion on their Github repo about that: https://github.com/facebook/jest/issues/2694, in case that can help you. – giuseppedeponte Oct 19 '19 at 08:41
-
Thanks. That does help. – terrible-coder Oct 20 '19 at 16:49
1 Answers
3
You can always assert against time difference
const start = performance.now();
doStuff();
const end = performance.now();
expect(end - start).toBeLessThen(3000); // < 3s
Meanwhile I agree with @giuseppedeponte it's definitely not a purpose for unit-testing frameworks. Especially because there is no way to guarantee the same performance between different runs.
Do profiling locally once you change flow. Run function for significant amount of times against edge cases' data. Make your conclusions. And unit testing is expected to validate if code's logic is valid.

skyboyer
- 22,209
- 7
- 57
- 64
-
It might have been nice to have everything under the same hood. However, since that is not the case, which benchmark tool would you recommend for a typescript/javascript project? I found [benchmark](https://www.npmjs.com/package/benchmark) and it seems to have a lot going on and hasn't been updated in 3 years. – terrible-coder Oct 20 '19 at 16:52
-
-
for those using nodejs, you will need the following import: import { performance } from "perf_hooks"; – Michel Dambros Figueiredo Jan 05 '23 at 10:39