Jest出现TypeError: Cannot read properties of undefined (reading 'randomUUID')解决方案

16 阅读1分钟

手动polyfill:

找到setupTests.js文件,添加以下代码:

window.crypto = {
  randomUUID: function () {
    return (
      [1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,
      c => (c ^ Math.floor(Math.random() * 255) & 15 >> c / 4).toString(16)
    );
  }
};

这样就可以在跑jest时全局替代crypto.randomUUID()的作用了