Mock window.crypto.getRandomValues in jest

Viewed 4684

I 'd like to mock window.crypto.getRandomValues in jest. I have tried jest.spyOn and it doesn't work out.

1 Answers

You could use Object.defineProperty to define the window.crypto property and its value.

E.g.

index.ts:

export function main() {
  let byteArray = new Uint8Array(1);
  return window.crypto.getRandomValues(byteArray);
}

index.test.ts:

import { main } from './';

describe('63484075', () => {
  it('should pass', () => {
    const mGetRandomValues = jest.fn().mockReturnValueOnce(new Uint32Array(10));
    Object.defineProperty(window, 'crypto', {
      value: { getRandomValues: mGetRandomValues },
    });
    expect(main()).toEqual(new Uint32Array(10));
    expect(mGetRandomValues).toBeCalledWith(new Uint8Array(1));
  });
});

unit test result with coverage report:

 PASS  src/stackoverflow/63484075/index.test.ts
  63484075
    ✓ should pass (6ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.759s, estimated 13s

source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63484075

Related