我正在通过电子邮件建立用户注册流程。我有一个TextInputScreen
组件,该组件向用户多次显示(以允许他/她输入电子邮件,密码和名称)。我通过EmailConnector
类控制此屏幕组件的显示和导航:
EmailConnector:
export default class EmailConnector {
localNavigation;
static inputViewModel = {
//viewModelFields like placeholder, error message etc.
};
//called from a different class, takes 'navigation' an input param
static openEmailScreen = async navigation => {
this.localNavigation = navigation;
//set viewModelFields
this.localNavigation.push('TextInputScreen', {
viewModel: this.inputViewModel,
inputValidator: () => this.emailReceived,//callback function
});
};
//called via a callback from the EmailConnector class.
static openPasswordScreen = () => {
//set viewModel fields
this.localNavigation.push('TextInputScreen', {
viewModel: this.inputViewModel,
inputValidator: () => this.passwordReceived,
});
};
请注意,openEmailScreen
与输入参数一样获得navigation
并设置this.localNavigation = navigation
。另一方面,在openPasswordScreen
中,我使用this.localNavigation
进行导航。
我想测试this.localNavigation.push()
方法中是否调用了openPasswordScreen
。我可以对openEmailScreen
进行此测试,因为我在测试中通过了navigation
作为输入参数。
但是,在openPasswordScreen
中,我使用了变量this.localNavigation
,但我不知道该如何模拟它。
这是我尝试过的:
it('Navigates to the password screen when the openPasswordScreen method is called', () => {
const localNavigationMock = {push: jest.fn()};
EmailConnector.openPasswordScreen(localNavigationMock);
expect(localNavigationMock.push).toHaveBeenCalledWith(
'TextInputScreen',
expect.objectContaining({
viewModel: expect.any(Object),
inputValidator: expect.anything(),
onAccessoryTap: expect.anything(),
}),
);
});
测试失败,并显示错误消息:Number of calls: 0
如何可靠地测试this.localNavigation.push()
函数中是否调用了openPasswordScreen()
?