fetch async data in composable - nuxtjs3

how can I use await with asyncdata in composable to get json array, below index.ts works but without awaits
export const arrHeightTable = () => useAsyncData( 'arrHauteurs', () => $fetch( 'https://hello.api/api/heightTable') );

Related

Jest testing mocking default constructor and static constant

I want to test the following code:
import messaging from '#react-native-firebase/messaging';
export const canRequestPushNotificationPermission = async () => {
return (
(await messaging().hasPermission()) ===
messaging.AuthorizationStatus.NOT_DETERMINED
);
};
I noticed that in order to test messaging() I needed to mock the default constructor like so:
jest.mock('#react-native-firebase/messaging', () => {
return () => ({
hasPermission: jest.fn(() => Promise.resolve(true)),
});
});
However this mocks the default constructor, how can I mock this constructor as well as the messaging.AuthorizationStatus.NOT_DETERMINED?
use spyOn to mock the getter of the property of object
see https://jestjs.io/docs/jest-object#jestspyonobject-methodname
for example,
jest.spyOn(messaging, 'AuthorizationStatus', 'get').mockReturnValue({NOT_DETERMINED: 1})

Firestore Collection Doesn't retrieve expected output

I have a react native function to to get all collection documents as follows
export const fetchAuctionItems = () => {
return firestore().collection('items').get();
};
When I'm accessing above function response not getting any documents instead that I'm getting following
Can anyone one help me to solve my problem, Thank you
collection.get() returns a a QuerySnapshot and this is the data you are seeing. You need to request the data from the QuerySnapshot, like so for example.
export const fetchAuctionItems = () => {
return firestore().collection('items')
.get()
.then(querySnapshot => querySnapshot
.docs
.map(d => ({
id: d.id,
...d.data(),
});
};
Read more about QuerySnapshot here

Testing a Redux action that dispatches 2 other functions with Jest?

I have a function (a Redux action) which calls 2 functions. I can't figure how how to test this with Jest:
This is my function:
import doSomething from 'redux/do-something';
import doSomethingElse from 'redux/do-something-else';
export default () => async dispatch => {
await dispatch(doSomething());
dispatch(doSomethingElse());
};
This is my test:
import doSomething from 'redux/do-something';
import doSomethingElse from 'redux/do-something-else';
import functionToTest from 'redux/function-to-test'
describe("functionToTest", ()=>{
jest.mock('redux/do-something');
jest.mock('redux/do-something-else');
const dispatch = jest.fn();
test('my test', ()=>{
functionToTest()(dispatch);
console.log(dispatch.mock.calls); // This returns an anonymous function
console.log(doSomething) // This returns undefined
})
})
It looks like you are wanting to mock the default export for do-something and do-something-else and test that they get dispatched by the code under test.
If that is the case then you can do it like this:
import functionToTest from 'redux/function-to-test'
jest.mock('redux/do-something', () =>
() => 'do something mock'
);
jest.mock('redux/do-something-else', () =>
() => 'do something else mock'
);
describe("functionToTest", () => {
test('my test', async () => { // <= async test function
const dispatch = jest.fn();
await functionToTest()(dispatch); // <= await the Promise
expect(dispatch.mock.calls[0][0]).toBe('do something mock'); // Success!
expect(dispatch.mock.calls[1][0]).toBe('do something else mock'); // Success!
});
});
Details
You can pass a module factory function as the second paramter to jest.mock and Jest will use the result of calling the function as what it gives back when the module is imported during the test.
jest.mock calls get hoisted by babel-jest and run before everything else in the code file. The hoisting doesn't work right when jest.mock is defined in a test function so the jest.mock calls should be moved to the top level scope of the test file.
The function under test is async so use an async test function and await the Promise to make sure it has completed before asserting.

Cloud Firestore Function returns only one document?

I create a firebase function to return posts collection, for some reason cloud function return only one post(document). But when I run this function locally, in terminal I get all posts. Any idea why?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});
admin.initializeApp();
exports.postWidget = functions.https.onRequest((request, response) => {
cors(request, response, () => {});
var db = admin.firestore();
var postsRef = db.collection('posts')
postsRef.where('postStatus', '==', 'published').get()
.then(snapshot => {
snapshot.forEach(doc => {
let data = doc.data()
return response.send(data)
});
})
.catch(err => {
console.log('Error getting documents', err);
});
});
You're calling response.send(data) multiple times in forEach loop. That's not likely to do what you want, as you're only supposed to call send() once with then entire response. Instead, you should be collecting all the data to send in a single object, and call send() with that one object.

Firebase Database Snapshot ForEach Async Await

async/await doesn't seem to work with firebase forEach. This code runs console.log for the first child of the snapshot and then just hangs. Is this a bug or am I missing something?
main()
async function main() {
const snap = await root.ref('somepath')
.once('value')
snap.forEach(async val => {
await console.log(val.key)
})
}
It's an unintentional consequence of a feature, sometimes knows as a bug. From the firebase documentation:
an async function always returns a Promise. And a promise is true-y value:
!!Promise.resolve===true.
As a workaround, try this solution:
main()
async function main() {
const snap = await root.ref('somepath')
.once('value')
snap.forEach(function wrapper(){async val => {
await console.log(val.key)
}})
It won't wait for the promise to complete before moving to the next snapshot though. That would require a bit more code, but that may not be what you need anyways.
I use something like this:
import * as admin from "firebase-admin";
type FunctionOnDataSnapshot = (childSnapshot: admin.database.DataSnapshot) => Promise<any>;
export const asyncForEach = async (dataSnapshot: admin.database.DataSnapshot, childFunction: FunctionOnDataSnapshot) => {
const toWait = [];
dataSnapshot.forEach(childSnapshot => {
toWait.push(childFunction((childSnapshot)));
});
await Promise.all(toWait);
};

Resources