React Native集成Redux与React Navigation的Login组件Jest测试报错求助
I’ve run into this exact issue before when testing components tied to React Navigation and Redux—let’s break down what’s going wrong and how to fix it.
The Root Cause
Your current mock for AppNavigator is exporting an object with an AppNavigator property, but your actual code imports the navigator as a default export. When reduxHelpers.js pulls in AppNavigator, it’s getting the entire mock object ({ AppNavigator: {...} }) instead of the navigator object itself. That’s why AppNavigator.router is undefined, triggering the getStateForAction error.
Step-by-Step Fix
Update your AppNavigator mock to match default export structure
Replace your existing mock with this—this ensures your code gets the mock navigator when using a default import:jest.mock("../../src/navigators/AppNavigator", () => ({ default: { router: { getStateForAction: jest.fn(() => ({ // Mock a valid initial navigation state if your code needs it index: 0, routes: [{ key: 'Login', routeName: 'Login' }] })), getActionForPathAndParams: jest.fn() } } }));Load the mock before dependent imports
Make sure thejest.mockcall sits at the top of your test file, before importingLogin,mockStore, or any redux-related files. This guarantees the mock is active when your reducers and store files load.Reuse the mock for reducer tests
For your reducer tests, you can either copy the samejest.mockcall to the top of those test files, or create a global mock to avoid repetition:- Create a file at
__mocks__/src/navigators/AppNavigator.js - Add this code to it:
module.exports = { default: { router: { getStateForAction: jest.fn(() => ({ index: 0, routes: [{ key: 'Login', routeName: 'Login' }] })), getActionForPathAndParams: jest.fn() } } };
Jest will automatically use this mock whenever
AppNavigatoris imported in any test file.- Create a file at
Updated Test Code Example
Here’s how your login test file should look after the fix:
import React from "react"; import { shallow } from "enzyme"; import Login from "../../src/screens/Login"; import mockStore from "../../__mocks__/redux-mock-store"; import { eventInitialState } from "../../src/redux/reducers"; // Mock AppNavigator with correct default export jest.mock("../../src/navigators/AppNavigator", () => ({ default: { router: { getStateForAction: jest.fn(() => ({ index: 0, routes: [{ key: 'Login', routeName: 'Login' }] })), getActionForPathAndParams: jest.fn() } } })); describe("Testing login screen", () => { it("renders as expected", () => { const wrapper = shallow(<Login />, { context: { store: mockStore(eventInitialState) } }); expect(wrapper.dive()).toMatchSnapshot(); }); });
内容的提问来源于stack exchange,提问作者otavio1992

