Как проверить обновление истории окна в хуке useEffect с Jest? - PullRequest
0 голосов
/ 10 апреля 2020

Мне трудно понять, как это проверить в Jest. Я исследовал насмешливое использование useEffect, но не добился успеха.

useEffect(() => {
    if (window != undefined) {
        window.history.pushState({
            id: 'myId'
        }, 'yes', getValue(myArg));
    }
}, [myArg]);

1 Ответ

0 голосов
/ 10 апреля 2020

Вот решение для универсального теста:

index.tsx:

import { useEffect } from 'react';

const getValue = (v) => v;

export function MyComponent() {
  const myArg = 'myArg';
  useEffect(() => {
    if (window != undefined) {
      window.history.pushState(
        {
          id: 'myId',
        },
        'yes',
        getValue(myArg),
      );
    }
  }, [myArg]);
  return null;
}

index.test.tsx:

import { MyComponent } from './';
import { mount } from 'enzyme';
import React from 'react';

describe('61130176', () => {
  it('should push state', () => {
    window.history.pushState = jest.fn();
    mount(<MyComponent></MyComponent>);
    expect(window.history.pushState).toBeCalledWith({ id: 'myId' }, 'yes', 'myArg');
  });
});

Результаты модульного теста с отчетом о покрытии:

 PASS  stackoverflow/61130176/index.test.tsx (9.369s)
  61130176
    ✓ should push state (35ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |       50 |     100 |     100 |                   
 index.tsx |     100 |       50 |     100 |     100 | 8                 
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.112s

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'enzyme',
  setupFilesAfterEnv: ['jest-enzyme', './jest.setup.js'],
  testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
  verbose: true,
};

исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61130176

...