我正在通过成功的api调用来测试函数的行为,我设法模拟了获取响应,但是then
回调内部的函数没有被调用,即使console.log显示函数正在运行在回调中。
我的测试在这里失败:
这是我正在测试的功能:
tryUserLogin() {
this.setState({loading: true});
const randomPassword = Math.random()
.toString(36)
.slice(-8);
const email = this.state.inputEmail;
const name = this.state.inputName;
const formData = new FormData();
formData.append('email', email);
formData.append('name', name);
formData.append('password', randomPassword);
const query = Util.urlForAddUser();
fetch(query, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
if (responseJson.code === 200) {
firebase.analytics().logEvent('userSuccessfulLogIn', {
userId: responseJson.response.id,
});
const userData = responseJson.response;
console.log('userData',userData) // <==== i can see this in console
this.storeUserData(userData, name);
this.setState({loading: false});
this.handleModalVisibility();
this.props.handelAddComment();
console.log('finish')
} else {
Alert.alert(
this.props.t('common:title_error'),
this.props.t('common:error'),
);
this.setState({loading: false});
}
})
.catch(error => {
firebase.crashlytics().log(
`error tryUserLogin
LoginModal===>> ${error.message}`,
);
Alert.alert(
this.props.t('common:title_error'),
this.props.t('common:error'),
);
this.setState({loading: false});
});
}
这是测试:
it('testing tryUserLogin code 200 case', async () => {
global.FormData = require('FormData');
global.fetch = jest.fn();
const userData = {
code: 200,
response: {
id: 1,
email: 'test+1234567890@t.com',
},
};
const name = 'test';
const email = 'test@t.com';
const spyStoreUserData = jest.spyOn(instance, 'storeUserData');
const spyHandelModalVisibility = jest.spyOn(
instance,
'handleModalVisibility',
);
fetch.mockImplementation(() => {
return Promise.resolve({
status: 200,
json: () => {
return Promise.resolve({
...userData,
});
},
});
});
instance.setState({inputName: name});
instance.setState({inputEmail: email});
await instance.tryUserLogin();
expect(spyStoreUserData).toBeCalledWith(userData.response, name);
expect(fetch.mock.calls[0][0]).toBe('testQuery');
expect(instance.state.loading).toBe(false);
expect(spyHandelModalVisibility).toBeCalled();
expect(mockHandelAddComment).toBeCalled();
});