首页 > 解决方案 > 开玩笑测试 React Native:找不到导航对象。您的组件是否在导航器的屏幕内?

问题描述

我正在尝试测试一个使用this.props.navigation. 这是组件或多或少的样子:

export class MyComponent extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
       //...
    };
  }

  async componentDidMount() {
    // ...
  }

  render() {
    //... some logic

    return (
      <Press
        onPress={() => {
           return this.props.navigation.navigate(Screen.EXAMPLE_SCREEN, {data: someData})
        }}
      />
    )
  }
}

我的测试看起来有点像这样:

const props = {
  route: {
    params: {
      data: {
        id: '0001',
      },
      moreData: {
        moreData: moreCoolData
      },
    },
  },
  // please notice the empty navigation object
  navigation: {},
} as any;

describe('<MyComponent />', () => {
  let wrapper: ShallowWrapper;

  describe.only('when loading', () => {

    it('should display an activity indicator', () => {
      wrapper = shallow(<MyComponent {...props} />);
      expect(wrapper.find(Loading)).toHaveLength(1);
      expect(wrapper.find(Loading).prop('title')).toEqual(`some string`);
    });
  });
}

当我运行这个测试时,我得到

Couldn't find a navigation object. Is your component inside a screen in a navigator?

      129 |
      130 |     return (props: any) => {
    > 131 |       const navigation = useNavigation();
          |                          ^
      132 |       return <MeasureHoc navigation={navigation} {...props} />;
      133 |     };
      134 |   };

我怀疑这是因为我navigation在道具中传递了一个空对象。如果真的是这样,道具中的那个“导航”obj应该是什么?

标签: reactjsreact-nativetestingjestjsenzyme

解决方案


推荐阅读