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

React Native测试出现TypeError: navigation.addListener未定义如何解决?

问题根源

你在测试中传入HomeScreen的navigation mock对象仅实现了push方法,但组件实际调用了addListener、navigate两个额外方法,缺失的方法导致运行时报错。

修复步骤

  1. 补全navigation mock对象,把所有用到的方法都通过jest模拟:
const mockNavigation = {
  push: jest.fn(),
  navigate: jest.fn(),
  // addListener返回的移除监听函数也需要模拟,符合React Navigation的接口定义
  addListener: jest.fn(() => jest.fn())
}
  1. 修复测试用例中的其他问题:
  • 第一个快照测试未给组件传navigation参数,需要传入mock对象
  • 第二个测试的断言文本和组件实际渲染文本不一致,需要对齐
  • 删除测试中未定义的console.log(navigation)语句,无意义且会报错
  • 删除RN测试不需要的ReactDOM导包

修正后完整测试代码

import '../../../matchMedia.mock';
import React from 'react';
import renderer from 'react-test-renderer';
import HomeScreen from '../HomeScreen';
import { render } from '@testing-library/react-native'
import { RecoilRoot } from 'recoil';

const mockNavigation = {
  push: jest.fn(),
  navigate: jest.fn(),
  addListener: jest.fn(() => jest.fn())
}

test('renders correctly', () => {
  const tree = renderer.create(<HomeScreen navigation={mockNavigation} />).toJSON();
  expect(tree).toMatchSnapshot();
});

test('renders default elements', () => {
  const { getAllByText } = render(<RecoilRoot><HomeScreen navigation={mockNavigation}/></RecoilRoot>);
  expect(getAllByText('What are we looking to drink?').length).toBe(1);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:36:04