【问题标题】:How to write a jest test for the router.listen callback如何为 router.listen 回调编写一个笑话测试
【发布时间】:2021-12-22 22:28:04
【问题描述】:

如何测试 router.listen 回调?

我有以下代码:

  if (router) {
    router.listen(() => {
      updatedResource = updateResource(resource, checkedOverrides);
    });
  }

我已经设法测试了 router.listen 方法的调用,但为了获得 100% 的覆盖率,我还需要测试是否调用了 updateResource 方法,该方法作为子导出导入到文件中。

import { updateResource } from 'path'

我试图监视它以查看它是否被调用,但这不起作用。以下是我目前编写的测试示例:

  it('should call the listen method when router exists.', () => {
    // const mockedUpdateResource = updateResource;
    // console.log(updateResource());

    const router = {
      listen: jest.fn(),
    };

    window.history.pushState({}, '', '/?Colour%20group=White');
    wrapper = shallow(<RangeParent consumer={consumer} resource={WCMSdata} router=    {router} />);

    // const spy = jest.spyOn(updateResource, 'updateResource');
    // window.history.pushState({}, '', '/');
    // const spy = jest.spyOn(updateResource);

    expect(router.listen).toHaveBeenCalled();
  });

【问题讨论】:

  • 能否提供router是如何在代码中导入的?
  • 当然,它的import { withRouter } from 'react-router';
  • withRouter 被用作 HOC 并包裹组件,将路由器作为组件的道具
  • 我想知道它是 router.listen 还是 history.listen?那听什么?
  • 基本上它会监听 url 的变化,我正在做的项目是使用旧版本的路由器

标签: reactjs jestjs react-router enzyme


【解决方案1】:

你正在监视 updateResource,而不是监视路径

import { updateResource } from 'path'

const mockUpdateResource = jest.spyOn(path, 'updateResource');

请尝试以下方法,

 const listenMock = jest.spyOn(router, 'listen');   
 listenMock.mockReturnValue(jest.fn());
 const listenCallback = listenMock.mock.calls[0][0]; //modify as per cb args 
 listenCallback();

或尝试嘲笑他们,

jest.mock('react-router', () => ({
  router: {
     listen: jest.fn(_=>)
  }
}));


jest.mock('path', () => ({
    updateResource: jest.fn()
}))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2018-07-08
    • 2019-02-12
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多