You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React侧边栏单元测试报错toBeInTheDocument不是函数如何解决

问题原因及解决方案

1. toBeInTheDocument is not a function 报错解决

该断言方法由@testing-library/jest-dom提供,单文件导入仍报错通常为两个原因:

  • jest执行顺序问题,单文件导入易失效,建议全局配置:
    1. 在jest.config.js中添加配置
    module.exports = {
      setupFilesAfterEnv: ['<rootDir>/src/setupTests.js']
    }
    
    1. 在src/setupTests.js中全局导入依赖
    import '@testing-library/jest-dom'
    
    配置后无需在每个测试文件单独导入该库。
  • 版本不兼容:若使用jest 28及以上版本,请确保@testing-library/jest-dom版本在5.16.2以上。

2. 渲染逻辑错误

当前代码混用了Enzyme的shallow浅渲染和Testing Library的查询能力,导致无法查到元素:
shallow是Enzyme提供的浅渲染方法,渲染结果仅保存在Enzyme的wrapper对象中,不会挂载到Testing Library对应的document上下文,因此调用screen.debug()会输出空内容,自然无法查询到渲染的文本。
要使用Testing Library的查询和断言能力,必须使用其自带的render方法渲染组件。

修改后的测试用例

针对校验侧边栏文本的测试用例,修改后代码如下:

it('render sidebar options as a text', () => {
    store = mockStore(initialProp);
    // 替换shallow为@testing-library/react的render方法
    render(
        <Provider store={store}>
            <Sidebar />
        </Provider>
    );
    const sidebarElement = screen.getByText('Application Manager');
    expect(sidebarElement).toBeInTheDocument();
});

额外注意点

Sidebar组件中handleProductSelection方法里的this.props.props.history.push写法存在错误,多写了一层.props,实际运行时会报错,建议修改为this.props.history.push,如果需要传入history参数,可在测试时用MemoryRouter包裹组件。

内容的提问来源于stack exchange,提问作者Siddhesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 19:06:02