如何开玩笑测试使用 performance.getEntries() 的函数?

时间:2021-05-20 08:41:35

标签: javascript node.js jestjs

在运行 jest 时,如果函数使用 performance.getEntries(或 performance.getEntriesByName),则测试会抛出异常:

performance.getEntries is not a function

如何让我的测试继续运行而不崩溃?


根据文档,performance.getEntries 已从 NodeJS v10.0.0 (https://github.com/nodejs/node/pull/19563) 的 perf_hooks 中删除,使用

可以实现相同的功能
const measures = []
const obs = new PerformanceObserver(list => {
  measures.push(...list.getEntries())
  obs.disconnect()
})
obs.observe({entryTypes: ['measure']})
function getEntriesByType(name) {
  return measures
}

然而,上述解决方案仅在直接在 NodeJS 应用程序中工作时才可行,在运行测试时不可行,因为我不想更改我的实现。我曾尝试将 performance.getEntries 模拟为 setupAfterEnv 中的全局变量,就像我对其他全局变量所做的那样。例如:

global.performance = {
  getEntries: () => []
}

但是在调试时,性能始终等于 {}(而 performance.now() 运行良好。我相信这是默认的 jsdom(这是我的 testEnvironment)。

0 个答案:

没有答案
相关问题