How to mock React Navigation's navigation prop for unit tests with TypeScript in React Native?

Issue

The mock does not match the expected type so TypeScript reports an error.

Solution

You can use the type any "to opt-out of type-checking and let the values pass through compile-time checks".

Details

As you mentioned, in JavaScript it works to mock only what is needed for the test.

In TypeScript the same mock will cause an error since it does not completely match the expected type.

In situations like these where you have a mock that you know does not match the expected type you can use any to allow the mock to pass through compile-time checks.


Here is an updated test:

import { LoadingScreen } from "./LoadingScreen";
import { shallow, ShallowWrapper } from "enzyme";
import React from "react";
import { View } from "react-native";

const createTestProps = (props: Object) => ({
  navigation: {
    navigate: jest.fn()
  },
  ...props
});

describe("LoadingScreen", () => {
  describe("rendering", () => {
    let wrapper: ShallowWrapper;
    let props: any;   // use type "any" to opt-out of type-checking
    beforeEach(() => {
      props = createTestProps({});
      wrapper = shallow(<LoadingScreen {...props} />);   // no compile-time error
    });

    it("should render a <View />", () => {
      expect(wrapper.find(View)).toHaveLength(1);   // SUCCESS
      expect(props.navigation.navigate).toHaveBeenCalledWith('LoginScreen');   // SUCCESS
    });
  });
});