Jest.js UnhandledPromiseRejectionWarning:TypeError:crypto.subtle.digest不是函数

wh6knrhe  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(146)

我在使用Jest对一个使用crypto. suggest.digest()进行散列的函数进行单元测试时得到“crypto. suggest.digest is not a function”。我使用JSDOM,我尝试了这两个选项,但没有运气:

1. `[How to use Jest to test functions using crypto or window.msCrypto][1]`

    Object.defineProperty(global.self, 'crypto', {
              value: {
                subtle: crypto.subtle,
              }
            });

字符串
1.第一个月

6qfn3psc

6qfn3psc1#

import { webcrypto } from 'crypto';
import { TextEncoder } from 'util';

import { digest } from './digest';

describe('digest', () => {
  beforeEach(() => {
    Object.defineProperties(global, {
      crypto: { value: webcrypto, writable: true },
      TextEncoder: { value: TextEncoder, writable: true },
    });
  });

  it('creates a SHA256 digest', async () => {
    expect(await digest('test')).toEqual(
      '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
    );
  });
});

字符串
digest.js:

async function digest(message, algo = 'SHA-256') {
  return Array.from(
    new Uint8Array(
      await crypto.subtle.digest(algo, new TextEncoder().encode(message))
    ),
    (byte) => byte.toString(16).padStart(2, '0')
  ).join('');
}

相关问题