【问题标题】:React, Snapshot Test useParams undefinedReact,快照测试 useParams undefined
【发布时间】:2021-10-05 23:47:31
【问题描述】:

我正在尝试为我的组件编写快照测试以响应 在我的组件中,我有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(``);
});

【问题讨论】:

标签: reactjs snapshot


【解决方案1】:

您需要将组件包装在 Router 中,useParams 使用来自路由器上下文的某些东西(可能是历史对象),没有路由器 - 没有上下文。

https://reactrouter.com/web/guides/testing

并且已经回答How to test components using new react router hooks?

【讨论】:

  • 我正在为我的组件使用路由。并让 tree = renderer .create( ) .toJSON();期望(树).toMatchInlineSnapsot(``);在我的 test.js 中
  • 不知道你为什么使用toJSON,通常我使用测试库,它有快照。 testing-library.com/docs/example-react-router 至少尝试只选择没有包装器的组件并对其进行快照。
  • 可能history.push有问题,可能尝试使用initialEntries
【解决方案2】:
const container = document.createElement('div');
 render(
      <MemoryRouter initialEntries={['/myroute/1']}>
        <Route
          exact
          path="/myroute/:id"
          component={() => (
            <>
              <ModuleDetails />
            </>
          )}
        />
      </MemoryRouter>,
      container
    );

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 2018-12-17
    • 1970-01-01
    • 2021-03-29
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多