Firebase Jest auth/network-request-failed' error - reactjs

I'm trying to do Firebase testing Using Jest. This is my test case.
test('Test Firebase Connection', done => {
let history = [];
function callback(history) {
expect(history[0]).toBe('/dashboard');
done();
}
firebaseDAO.init('myEmail', 'mypassword', history);
setTimeout(callback, 4000,history);
});
export const init = (username, passwordPassed, history) => {
let historyData = history;
const email = username;
const password = passwordPassed;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);
promise.catch(e => console.log(e));
promise.then(() => {historyData.push('/dashboard');});
};
When I run the test with Idea-Webstorm-Jest Plugin it Works. (Test passes.)
But when I try with npm Test command. Firebase gives me following Error.
{code: 'auth/network-request-failed',
message: 'A network error (such as timeout, interrupted connection or unreachable host) has occurred.' }
So why it is fails when npm Test command runs? Anyone can help me? thanks in advance.

I had that problem too, i looked for google and i found that my input or button in html was in type:"submit" which made the page refresh, it's better to do type"button"

Related

Problem with listening to messages OnSnapshot with a React Native Firebase Messaging App

I'm trying to create a React Native messaging app with the firebase SDK. In the chat screen I am trying to listen to updated messages in my firestore database. I'm following a lot of the code shown in this github repository https://github.com/ReactNativeSchool/react-native-firebase-chat-app, but it uses react-native-firebase and I am using the SDK which is causing making it hard for me to find the equivalent code with the firebase SDK. What am I doing wrong in the below code that is giving me the following error when I open the screen:
undefined is not a function (near '...(0,_firebaseConfig.listenToMessages)(threadID).onSnapshot...')
I believe it has to do with me not converting from react-native-firebase to the firebase SDK correctly, but I'm not sure.
Below is my listenToThreads code from the firebaseConfig file where I do all my firebase functions. Below that is the part I commented out that returned the values within that collection.
export const listenToMessages = async (threadID) => {
return firebase.firestore()
.collection('threads')
.doc(threadID)
.collection('messages');
// try {
// const q = query(collection(db, "threads"), where("tid", "==", threadID));
// const doc = await getDocs(q);
// const data = doc.docs[0].data();
// return data.messages;
// } catch {
// return [];
// }
};
and here is my onSnapshot code which I'm running inside a working UseFocusEffect hook.
const unsubscribe = listenToMessages(threadID).onSnapshot(
querySnapshot => {
const formattedMessages = querySnapshot.docs.map(doc => {
return {
_id: doc.id,
text: '',
createdAt: new Date().getTime(),
user: {}
};
});
setMessages(formattedMessages);
},
);
return () => {
unsubscribe();
};
The listenToMessages function should not be async.
It returns a promise rather than the doc you want. ✌️

FetchError: request failed

I have a bug, i'm trying to make his tutorial for twitter clone in nextjs+tailwindcss+typescript
https://www.youtube.com/watch?v=rCselwxbUgA&t=1357s&ab_channel=SonnySangha
1:42:05 / 3:17:52
I did exactly the same but i feel like my IDE or my nextJS version is making things different
import { Tweet } from "../typings"
export const fetchTweets = async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
FetchError: request to https://localhost:3000/api/getTweets/ failed,
reason: write EPROTO 140020696905664:error:1408F10B:SSL
routines:ssl3_get_record:wrong version
number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
This error happened while generating the page. Any console logs >will be displayed in the terminal window.
import { Tweet } from "../typings"
export const fetchTweets = async () => {
if(global.window) {
const res = await
fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
}
Server Error Error: Error serializing .tweets returned from
getServerSideProps in "/". Reason: undefined cannot be serialized
as JSON. Please use null or omit this value.
If someone can help me <3 thanks
FIXED :
.env.local
i writed
NEXT_PUBLIC_BASE_URL=https://localhost:3000/
change https:// by http:// and yarn run dev again
NEXT_PUBLIC_BASE_URL=http://localhost:3000/

MSAL: InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache. Please sign-in

Here's the bit of code that I was working on. I am using MSAL for two SSO apps on same domain for example https://some-domain.com/app1 and https://some-domain.com/app2 and please see the code snippet below.
App 1 seems to be fine it allows user to sign in correctly.However, on app2 when I reload the page it throws an error
MSAL: InteractionRequiredAuthError: no_tokens_found: No refresh token
found in the cache. Please sign-in.
I have used instance.acquireTokenRedirect,acquireTokenSilent and identityInstance.loginRedirect() but nothing seemed to work. Any ideas please share. Thanks.
const [userName, setUsername] = useState<string | undefined>()
useEffect(() => {
const fetchDetaiils = async () => {
if (inProgress === InteractionStatus.None) {
try {
const signedInUser = identityInstance.getAllAccounts()[0]
const resp = await identityInstance.acquireTokenSilent({
scopes: ['user.read'],
account,
})
const token: Token = resp?.idTokenClaims
setUsername(token.email)
} catch (err: unknown) {
if (err instanceof Error) {
console.log(err)
if (err?.name === 'InteractionRequiredAuthError') {
// await instance.acquireTokenRedirect(loginRequest)
}
}
}
}
}
fetchDetaiils()
As described in these Microsoft Docs, SSO between apps requires the use of either the login_hint or sid (session ID) parameters in the silent request.
The values of login_hint and sid can be extracted from the ID Token that is obtained in App 1. For more information, please consult the MSAL Browser Login Docs

How to test signin component with jest and react testing library

I try to create an integrated test for a sign in component but I am facing some issues. Basically I need to check that after entered email and password credentials and clicked the submit button, it redirect me to a given page. I am using waitForComponentToBeRemoved to check the none presence of email or password field of the sign in component but I got an error:
Timed out in waitForElementToBeRemoved.
Please tell me if i dont have the right approach or if you need further informations.
Here is the test:
it( 'Login with real username and password', async () => {
beforeEach(() => {
fetch.dontMock()
})
act(() => {
ReactDOM.render(<App />, container);
})
// log /
console.log('history', window.location.pathname)
const email = process.env.TEST_EMAIL
const password = process.env.TEST_PASSWORD
const signInButton = screen.getByTestId('landing-signin')
fireEvent.click(signInButton)
await waitFor(async () => {
expect(signInButton).not.toBeInTheDocument()
// log /signin
console.log('history', window.location.pathname)
})
const emailField = screen.getByPlaceholderText('Email address')
const passwordField = screen.getByPlaceholderText('Your password')
const button = screen.getByTestId('submit-button')
expect(button).toBeInTheDocument()
expect(passwordField).toBeInTheDocument()
expect(emailField).toBeInTheDocument()
userEvent.type(emailField, email)
userEvent.type(passwordField, password)
await act(async () => {
fireEvent.click(button)
})
// Timed out in waitForElementToBeRemoved.
await waitForElementToBeRemoved(button).then(() => {
console.log('element has been removed')
})
// i need something to wait the response and the redirection to be done
})
ps: I dont want to mock data, it need to do real api call
How to you do the redirect in your source code? Are you using react-router? (In this case you could simply mock the redirect function and check if it has been called!?)
Please check out this related question: Testing redirect after submit with React Testing Library
Kent C Dodds is building and testing a simple sign-in component in this video (starting at timestamp 14:30):
https://www.youtube.com/watch?v=eg_TFYF_cKM&t=869s&ab_channel=Applitools%3AVisualAIPoweredTestAutomation

An error occurred when I get a data from firestore in React app

I'm developing a task management app with Firebase and React.
Current Code
export const login = (type, email, password) => dispatch => {
dispatch({type: "LOGIN"});
switch (type) {
case "EMAIL": {
// Logging in using Firebase Auth. It goes successfully.
firebase.auth().signInWithEmailAndPassword(email, password).then(result => {
const db = firebase.firestore();
const uid = result.user.uid
// Getting user name from Firestore. The fllowing error occurs here.
let name;
db.collection("users").get().then(querySnapshot => {
querySnapshot.forEach(doc => {
name = doc.name;
dispatch({type: "LOGIN_SUCCEEDED", uid: uid, name: name,});
dispatch(push("/"))
});
}).catch(err => {
dispatch({type: "LOGIN_REJECTED", error: err});
});
}).catch(err => {
dispatch({type: "LOGIN_REJECTED", error: err.message});
});
break;
}
default: {}
}
Only the code of the relevant part here.
Other codes are in Github.
Auth(Firebase)
Firestore
The error occured
[2020-06-07T03:54:57.645Z] #firebase/firestore: Firestore (7.15.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unknown]: Fetching auth token failed: getToken aborted due to token change.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend. index.js:1
I tried this to solve the error:
Check the network => It is healthy. I can see any pages on the internet and even connect to firebase auth in same program.
Use older virsion Firebase => nothing changed.
This is caused because the user is already logged, do something like this and will work:
if (!firebase.auth().currentUser) {
await firebase.auth().signInWithEmailAndPassword(email, password);
}
Obs: To use await, you will need a async function
Hope it help :)

Resources