【问题标题】:`IonRouterOutlet` does not deep render in Ionic-React snapshot testing`IonRouterOutlet` 在 Ionic-React 快照测试中没有深度渲染
【发布时间】:2021-02-22 10:15:42
【问题描述】:

我正在尝试对由 Ionic React 路由器包装的组件进行快照并执行深度渲染。但在我的情况下,IonicRouterOutlet 似乎并没有进行深度渲染。有什么建议可以解决这个问题并成功执行深度渲染吗?

这是我的示例代码:

import React from 'react'
import { render } from '@testing-library/react'
import { IonRouterOutlet } from '@ionic/react'
import { IonReactRouter } from '@ionic/react-router'

jest.mock('@capacitor/core', () => ({
  Plugins: {
    StatusBar: {
      setStyle: jest.fn()
    },
    Storage: {
      set: jest.fn(),
      get: () => ""
    }
  },
  StatusBarStyle: {
    Light: "LIGHT"
  },
}));

describe('component', () => {
  let component

  beforeEach(async () => {
    component = render(
      <IonReactRouter>
        <IonRouterOutlet>
          <div />
        </IonRouterOutlet>
      </IonReactRouter>
    )
  })

  describe('snapshot', () => {
    it('should match snapshot', () => {
      const { asFragment } = component
      expect(asFragment()).toMatchSnapshot()
    })
  })
})

这是我的快照输出:

exports[`Login component snapshot should match snapshot 1`] = `
<DocumentFragment>
  <ion-router-outlet />
</DocumentFragment>
`;

如您所见,&lt;div /&gt; 不会在快照输出中生成。那么如何解决这个问题呢?

【问题讨论】:

  • 你在某处模拟 Ionic React 组件吗?
  • @juliomalves 有一个模拟功能,是的。我刚刚更新了上面的代码。请看一看。谢谢。

标签: javascript reactjs ionic-framework jestjs react-testing-library


【解决方案1】:

我找到了我认为会有所帮助的文档https://github.com/crossroads/app.goodchat.hk/wiki/Testing-Routing

基本上,正如您发现的那样,使用 IonReactRouter 和 IonRouterOutlet 会导致 JSDOM 输出 &lt;ion-router-outlet /&gt; 而不是完整的树。

解决方法是直接使用 React Router 的 Router 和 MemoryRouter,具体取决于您要访问的内容,例如 history.location.pathname。 IonReactRouter 在底层使用 React Router,因此行为和 JSDOM 输出应该匹配。

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 2012-11-28
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-22
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多