我正在使用Jest和React Test Renderer来测试React Native组件,其中我向安装时的react-navigation对象添加了一些参数,如下所示:
componentDidMount() {
const { setParams } = this.props.navigation;
setParams({ subTitle: this.props.user.outlet.name.toUpperCase() });
}
这在用户界面中工作正常,但是在测试中我收到错误TypeError: Cannot read property 'outlet' of undefined
通过navigation
作为道具可以正常工作,但我想我没有正确通过user
。我在做什么错了?
这是我的测试(我认为没有相关的任何内容):
const props = {
navigation: {
navigate: jest.fn()
},
user: {
// user info here
}
};
const tree = renderer.create(
<MockApp mocks={{ ...baseMocks, ...mocks }}>
<Home {...props} />
</MockApp>
);
await wait(0);
expect(tree.toJSON()).toMatchSnapshot();
答案 0 :(得分:0)
更新:
也许不是一个完美的解决方案,但是鉴于我首先不明白为什么会失败,所以我通过检查组件中user
的存在使测试通过:
user &&
user.outlet &&
navigation.setParams({ subTitle: user.outlet.name.toUpperCase() });
很希望有人能解释为什么它最初并没有奏效...