【问题标题】:How to implement jest unit test with react-navigation如何使用 react-navigation 实现 jest 单元测试
【发布时间】:2018-05-08 01:07:05
【问题描述】:

我目前正在为 react-navigation 添加 jest 单元测试,例如: 我的 StackNavigator

const Nav = StackNavigator({
    Home: {
        screen: Home,
    },

    Second: {
        screen: Second,
    }
});

export default class App extends Component<{}> {
  render() {
    return (
      <Nav/>
    );
  }
}

我的主页组件

export default class Home extends Component<{}> {

    _goToNextPage = () => {
        this.props.navigation.navigate('Second');
    }

    render() {
        return (
            <View>
                <Text>Home</Text>
                <Button
                    onPress={this._goToNextPage}
                    title="Go to Second Page"
                >Click to next page</Button>
            </View>
    );
    }
}

我的第二个组件 导出默认类 Second 扩展组件 {

render() {
    return (
        <View>
            <Text>Second</Text>
        </View>
    );
}

}

我应该如何编写有趣的单元测试来测试“当我单击 GoToNextPage 按钮时,第二个组件应该正确呈现?”

我没有找到任何关于 jest 与 react-navigation 的有用信息,任何帮助将不胜感激!!!

非常感谢~

【问题讨论】:

    标签: react-native jestjs react-navigation


    【解决方案1】:

    我个人很喜欢 @testing-library/react,因为他们的理念是从用户角度进行测试。我想你的测试看起来像下面这样:

    it('shows the second component when the next button is clicked', async () => {
      // Renders your app
      const { getByText, findByText } = render(<App />);
      // Clicks your button
      fireEvent.click(getByText('Click to next page'));
      // Waits for the 'Second' text to be visible, could be async or sync, in this
      // case I'm using the async expectation style
      await wait(() => expect(getByText('Second')));
    });
    

    我将通过简单地渲染第二个组件并根据您的快照检查它来将点击按钮的关注点和它正确渲染的验证分开的方式进行测试。

    // inside your second component test - still using testing-library
    it('matches the snapshot', () => {
      expect(render(<Second />).container).toMatchSnapshot();
    });
    

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 2018-02-15
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      相关资源
      最近更新 更多