我在redux操作中调用react-navigation NavigationService。测试我需要模拟导航功能的操作。
/app/utils/NavigationService.js
import { NavigationActions } from 'react-navigation';
let navigator;
function setTopLevelNavigator(navigatorRef) {
navigator = navigatorRef;
}
function navigate(routeName, params) {
navigator.dispatch(NavigationActions.navigate({
type: NavigationActions.NAVIGATE,
routeName,
params,
}));
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
};
我创建了一个紧邻NavigationService.js文件的__mock__
文件夹。
app/utils/__mocks__/NavigationService.js
更新
const navigate = jest.fn();
const setTopLevelNavigator = jest.fn();
export default {
navigate,
setTopLevelNavigator,
};
为什么在测试运行时jest自动模拟navigate
函数? https://jestjs.io/docs/en/manual-mocks
__tests__/actions/AuthActions.test.js
更新
jest.mock('../../app/utils/NavigationService'); //at the top directly behind other imports
it('should call firebase on signIn', () => {
const user = {
email: '[email protected]',
password: 'sign',
};
const expected = [
{ type: types.LOGIN_USER },
{ payload: 1, type: types.DB_VERSION },
{ payload: 'prod', type: types.USER_TYPE },
{ payload: { name: 'data' }, type: types.WEEKPLAN_FETCH_SUCCESS },
{ payload: { name: 'data' }, type: types.RECIPELIBRARY_FETCH_SUCCESS },
{
payload: { user: { name: 'user' }, userVersionAndType: { dbVersion: 1, userType: 'prod' } },
type: types.LOGIN_USER_SUCCESS,
},
];
return store.dispatch(actions.loginUser(user)).then(() => {
expect(store.getActions()).toEqual(expected);
});
});
app/actions/AuthActions.js
export const loginUser = ({ email, password }) => (dispatch) => {
dispatch({ type: LOGIN_USER });
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch((signInError) => {
dispatch({ type: CREATE_USER, payload: signInError.message });
return firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(async (user) => {
const userVersionAndType = await dispatch(initUser());
await dispatch(initWeekplan(userVersionAndType));
await dispatch(initRecipeLibrary(userVersionAndType));
return user;
});
})
.then(async (user) => {
saveCredentials(email, password);
const userVersionAndType = await dispatch(getUserVersionAndType());
await dispatch(weekplanFetch(userVersionAndType));
await dispatch(recipeLibraryFetch(userVersionAndType));
dispatch(loginUserSuccess({ user, userVersionAndType }));
NavigationService.navigate('Home');
})
.catch(error => dispatch(loginUserFail(error.message)));
};
你创造了一个manual mock for a user module。
激活特定测试文件的用户模块的手动模拟需要调用jest.mock
。
对于这个特殊情况,将此行添加到__tests__/actions/AuthActions.test.js
的顶部,mock将用于该测试文件中的所有测试:
jest.mock('../../app/utils/NavigationService'); // use the manual mock in this test file
请注意,必须通过调用fs
为特定测试文件激活用户模块和节点核心模块(如path
,util
,jest.mock
等)的手动模拟,并且此行为与Node模块的手动模拟不同它们会自动应用于所有测试。