如何使用Jest测试useEffect挂钩中的更新窗口历史记录

时间:2020-04-09 21:03:55

标签: reactjs jestjs react-hooks use-effect ts-jest

我在弄清楚如何在Jest中进行测试时遇到了麻烦。我已经探索过嘲笑useEffect,但是没有成功。

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

1 个答案:

答案 0 :(得分:0)

这是uni测试解决方案:

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