【问题标题】:react jest mock useNavigate()反应开玩笑模拟 useNavigate()
【发布时间】:2021-05-22 20:11:06
【问题描述】:
"react-router-dom": "^6.0.0-alpha.5",

我几乎尝试了所有方法。

我只想模拟来自useNavigate() 钩子的navigate() 调用。而已。简单的。没有任何效果。

不,我不想使用Link。 useNavigate 在其他地方也以编程方式使用,我也想模拟它们

import React from 'react'
import { useNavigate } from "react-router-dom"

export const Detail = () => {
    const navigate = useNavigate();
    return (
        <span onClick={() => navigate('/some/specific/route')}>
            some Text
        </span>
    )
}

我试过这些:

jest.mock('react-router-dom', () => {
    // Require the original module to not be mocked...
    const originalModule = jest.requireActual('react-router-dom');

    return {
        __esModule: true,
        ...originalModule,
        // add your noops here
        useNavigate: jest.fn(() => 'bar')
    };
});
import * as ReactRouterDom from "react-router-dom";
...
// cannot redefine property
          Object.defineProperty(ReactRouterDom, 'useNavigate', {
              configurable: true,
              value: jest.fn(() => 'bar')
          });
// doesnt work
          jest.mock('react-router-dom', () => ({
              useNavigate: jest.fn(() => jest.fn),
          }))
// doesnt work
jest.spyOn(ReactRouterDom, 'useNavigate', 'get').mockReturnValue(jest.fn(() => jest.fn));
// doesnt work
jest.spyOn(ReactRouterDom, 'useNavigate').mockReturnValue(jest.fn(() => jest.fn));
// doesnt work
const mockedUsedNavigate = jest.fn();

jest.mock('react-router-dom', () => ({
   ...jest.requireActual('react-router-dom') as any,
  useNavigate: () => mockedUsedNavigate,
}));

所有这些要么显示"Cannot redefine Property 'useNavigate'",要么显示 useNavigate() may be used only in the context of a &lt;Router&gt; component.

说真的,任何其他导入模拟都可以正常工作。

我做错了什么?

我的最小重建项目:https://github.com/zacharytyhacz/useNavigateBug

【问题讨论】:

    标签: reactjs jestjs mocking react-hooks react-router-dom


    【解决方案1】:

    我有一个类似的问题,this issue from react router 解决了

    我建议您按原样更改模拟:

    // pay attention to write it at the top level of your file
    const mockedUsedNavigate = jest.fn();
    
    jest.mock('react-router-dom', () => ({
       ...jest.requireActual('react-router-dom') as any,
      useNavigate: () => mockedUsedNavigate,
    }));
    
    
    // your describe/it/test blocks go down there
    
    

    【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2014-09-18
    • 2020-03-05
    相关资源
    最近更新 更多