如何在React中用Jest和酶测试此类组件?

时间:2019-11-10 08:37:26

标签: reactjs jestjs enzyme

我有一个React Scroll to Top组件,我们在Router的下面添加了这个组件,这样在跨页面移动时我们不会保持滚动位置。

我试图为此组件编写测试用例,但Jest和Enzyme代理在进行浅层渲染时似乎将其识别为组件。我正在使用打字稿,这就是组件。

scrollToTop.ts

export const ScrollToTop = ({history}: IRouterResetScroll) => {
  useEffect(() => {
    const unListen = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unListen();
    }
  }, []);

  return null;
}

export default withRouter(ScrollToTop);

1 个答案:

答案 0 :(得分:1)

这是我的单元测试策略,要测试的代码中最难的部分是history.listen(handler),因此我们可以模拟history.listen方法的实现,我们将queue定义为存储处理程序。装入组件后,模拟的历史记录将以函数作为参数执行history.listen。此函数将存储在我们之前定义的queue中。我们可以从单元测试用例的队列中获取此功能,然后手动触发它。

index.tsx

import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

type IRouterResetScroll = any;

export const ScrollToTop = ({ history }: IRouterResetScroll) => {
  useEffect(() => {
    const unListen = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unListen();
    };
  }, []);

  return null;
};

export default withRouter(ScrollToTop);

index.spec.tsx

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

describe('ScrollToTop', () => {
  it('should scroll to top', () => {
    const queue: any[] = [];
    const mUnListen = jest.fn();
    const mHistory = {
      listen: jest.fn().mockImplementation(fn => {
        queue.push(fn);
        return mUnListen;
      })
    };
    window.scrollTo = jest.fn();
    const wrapper = mount(<ScrollToTop history={mHistory}></ScrollToTop>);
    queue[0]();
    expect(mHistory.listen).toBeCalledWith(expect.any(Function));
    expect(window.scrollTo).toBeCalledWith(0, 0);

    wrapper.unmount();
    expect(mUnListen).toBeCalledTimes(1);
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/58786973/index.spec.tsx
  ScrollToTop
    ✓ should scroll to top (39ms)

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

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58786973

相关问题