Я создал SignUp с firebase как store и redux-saga для обработки побочных эффектов (вызов Api), вот как это выглядит:
user-saga. js
import { takeLatest, put, call, all } from 'redux-saga/effects';
import { auth } from '../../utility/firebase/firebase.utils';
import userActionsTypes from './user.types';
import { signUpSuccess, signUpFailure } from './user.actions';
export function* isSignUpStart({payload:{displayName, email, password}}) {
try {
const { user } = yield auth.createUserWithEmailAndPassword(email,password);
yield put(signUpSuccess({ user, additionalData: { displayName } }));
} catch (error) {
yield put(signUpFailure(error));
}
}
// watcher
export function* onSignUpStart() {
yield takeLatest(userActionsTypes.SIGN_UP_START, isSignUpStart);
}
saga.test. js
В тесте я слушаю действия, используя recordSaga, и пытаюсь смоделировать пожарную базу, чтобы проверить вызывается createUserWithEmailAndPassword или нет. - эта логика c теста верна? потому что все всегда toHaveBeenCalled()
возвращается 0
import { runSaga } from 'redux-saga';
import * as firebase from 'firebase'
import { onSignUpStart, isSignUpStart } from '../user.sagas';
import userActionsTypes from './user.types';
jest.spyOn(firebase, 'initializeApp')
.mockImplementation(() => {
return {
auth: () => {
return {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
currentUser: {
sendEmailVerification
},
signInWithRedirect
}
}
}
});
jest.spyOn(firebase, 'auth').mockImplementation(() => {
return {
onAuthStateChanged,
currentUser: {
displayName: 'testDisplayName',
email: 'test@test.com',
emailVerified: true
},
getRedirectResult,
sendPasswordResetEmail,
createUserWithEmailAndPassword
}
});
const createUserWithEmailAndPassword = jest.fn(() => {
return Promise.resolve('result of createUserWithEmailAndPassword')
});
export async function recordSaga(saga, initialAction) {
const dispatched = [];
await runSaga(
{
dispatch: action => dispatched.push(action)
},
saga,
initialAction
).toPromise();
return dispatched;
}
describe('testing isSignUpStart saga', () => {
it ('Should return error if failed (passowrd < 6 or email exist)', async () => {
const initialAction = {
payload:{displayName:'bidsflal', email:'bivlal@gmail.com', password: '12345678'}
};
const dispatched = await recordSaga(
isSignUpStart, // saga to test
initialAction
);
expect(dispatched[0].type).toEqual(userActionsTypes.SIGN_UP_FAILURE);
expect(firebase.auth).toHaveBeenCalled()
});
it ('Should success ', async () => {
const initialAction = {
payload:{displayName:'oigdfgsflal', email:'oioioioio@gmail.com', password: '12345678'}
};
const dispatched = await recordSaga(
isSignUpStart, // saga to test
initialAction
);
expect(dispatched[0].type).toEqual(userActionsTypes.SIGN_UP_SUCCESS);
expect(createUserWithEmailAndPassword).toHaveBeenCalled();
});
});