首页 > 解决方案 > React,快照测试 useParams undefined

问题描述

我正在尝试为我的组件编写一个快照测试在我的组件中我有useParams() 运行测试时它返回一个未定义的错误:

TypeError: Cannot read property 'match' of undefined

  20 |   const [value, setValue] = useState();
  21 |   const { show, changeDetails } = props;
> 22 |   const { id } = useParams();
     |                  ^

组件位于

  <Switch>
      <Route
        exact
        path="/myroute/:id"
        component={() => (
          <>
            <ModuleDetails />
          </>
        )}
      />
    </Switch>

和 test.js 就像

it('renders correctly the assessment show page', () => {
  const history = createMemoryHistory();
  history.push('/myroute/1');
  let tree = renderer
    .create(
      <Router history={history}>
        <ModuleDetails />
      </Router>
    )
    .toJSON();
  expect(tree).toMatchInlineSnapsot(``);
});

标签: reactjssnapshot

解决方案


const container = document.createElement('div');
 render(
      <MemoryRouter initialEntries={['/myroute/1']}>
        <Route
          exact
          path="/myroute/:id"
          component={() => (
            <>
              <ModuleDetails />
            </>
          )}
        />
      </MemoryRouter>,
      container
    );

推荐阅读