微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Jest 中模拟路由器

如何解决在 Jest 中模拟路由器

我有下面的简单示例,我尝试更改 withRouter 的模拟实现。不幸的是,这似乎没有按预期工作。根本不会调用第二个模拟实现。

组件

import { withRouter } from 'next/router';

const PaymentChange = ({ router }) => {
  console.log(router);
  return <></>;
};

export default withRouter(PaymentChange);

测试文件

import { render } from '@testing-library/react';
import { withRouter } from 'next/router';
import PaymentChange from './PaymentChange';
import '@testing-library/jest-dom/extend-expect';

jest.mock('next/router',() => ({
  withRouter: jest.fn().mockImplementation((component) => {
    component.defaultProps = {
      ...component.defaultProps,router: { pathname: 'mocked-path' }
    };
    return component;
  })
}));

describe('<PaymentChange />',() => {
  it('Should not render modal when retargetModal',() => {
    withRouter.mockImplementation((component) => {
      component.defaultProps = {
        ...component.defaultProps,router: { pathname: 'mocked-pathasdasd' }
      };
      return component;
    });

    render(<PaymentChange />);
  });
});

输出

{ pathname: 'mocked-path' }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。