简体   繁体   English

在 Jest 中计时 function 调用

[英]Timing function calls in Jest

I am trying to develop some code for my own library.我正在尝试为我自己的库开发一些代码。 I chose Jest as the testing framework.我选择 Jest 作为测试框架。 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.我想做的是有测试用例来确保特定的 function 不会花费太多时间来执行。 Basically that requires some way of timing how much time a function call is taking.基本上,这需要某种方式来计算 function 调用所花费的时间。 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.但是,让 Jest 完成这项工作可能会很好。 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.我曾尝试调查 Github Jest 存储库上的(开放和封闭)问题,但我找不到任何特别解决我问题的东西。 Does anyone know of such a way of timing function calls with Jest?有谁知道用 Jest 调用 function 的这种计时方式?

You can always assert against time difference你总是可以断言时差

const start = performance.now();
doStuff();
const end = performance.now();
expect(start - end).toBeLessThen(3000); // < 3s

Meanwhile I agree with @giuseppedeponte it's definitely not a purpose for unit-testing frameworks.同时,我同意@giuseppedeponte 的观点,这绝对不是单元测试框架的目的。 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.针对边缘情况的数据运行 function 大量时间。 Make your conclusions.得出你的结论。 And unit testing is expected to validate if code's logic is valid.并且单元测试有望验证代码的逻辑是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM