Unexpected text "return" - firebase

I'm trying to implement an AuthService from a tutorial of Fireship (https://fireship.io/lessons/flutter-firebase-google-oauth-firestore/)
I copied exactly his AuthService:
AuthService() {
user = Observable(_auth.onAuthStateChanged);
profile = user.switchMap((FirebaseUser u) => {
if (u != null) {
return _db.collection("users").document(u.uid).snapshots().map((snap) => snap.data);
} else {
return Observable.just({});
}
});
}
I get these errors:
If I copy the code from his website (it's exactly the same) there are no errors.
wtf? Can someone explain this or help? Thanks!

Change this:
profile = user.switchMap((FirebaseUser u) => {
into this:
profile = user.switchMap((FirebaseUser u) {
From the docs:
For functions that contain just one expression, you can use a shorthand syntax:
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;
The => expr syntax is a shorthand for { return expr; }. The => notation is sometimes referred to as arrow syntax.

Related

How can I check URL content with Cypress

I want to check my URL content and do something like this:
if (URL.include('path')) {
//do something
} else {
// do something else
}
I can check my URL like this
cy.url().should('include', 'path');
but when I am pasting it in if operator it is not working.
Will recommend you to use .includes() method. It determines whether a string contains the characters of a specified string:
const path = 'user/survey';
cy.url().then(($url) => {
if($url.includes(path)) {
cy.log("Yes")
} else {
cy.log("No")
}
})
You can combine location() with then().
Here is how I do it:
cy.location('pathname').then((loc) => {
if(loc == '/my/path') {
...do
} else {
...smth else
}
})
I hope it solves your issue,
Best
I found The answer, but its vary long. Any ideas pls.
cy.url().then(url => {
const currentURL = url.split('/path/');
const pathURL = currentURL[1];
if(pathURL === 'user/survey')
{
cy.log('aaaaaaaaaa')
} else {
cy.log('bbbbbbbbb')
}
})

why map with condition return always value

I'm using rxjs map to retrive data in firestore like this:
getArtists(): Observable<DocumentData> {
const users$ = this.firestore.collection('/Users').get()
users$.subscribe((users) => {
users.docs.map(user => user.data().artistName !== "" && user.data().role === 'ARTIST')
});
return users$;
}
but when i'm getting value like this :
this.userService.getArtists().subscribe(
(userDocs) => {
userDocs.docs.map((user) => {
this.artists.push(user.data());
console.log(this.artists)
this.record = this.artists.length;
})
});
it's return always the user when the artistName is equals to "" and role is not equals to 'ARTIST'.
why ?
thank's everybody!
you need to map data in a map operator instead of a subscription and return a value in as a pipe.
Unfortunately, in your code isn't clear what and when you want to filter, why a user is in users.docs when it tend to be a doc.
Please check an example below and consider updating your question with more info.
import {filter, map} from 'rxjs/opreators';
getArtists(): Observable<DocumentData> {
return this.firestore.collection('/Users').get().pipe( // <- use pipe
map(users => {
// here some changes in users if we need.
return users;
}),
),
filter(users => {
returns true; // or false if we don't want to emit this value.
}),
}

AngularFire2 Firebase Observable never ends (list is empty)

I'm trying to query an empty firebase list. The problem is that the observable method subscribe never finish and I can't show to user that ddbb list is empty.
The function getUserAppointmentsByDate(...) is calling getUserAppointments(...), where this.database.list('/appointment/users/' + user_uid) is an empty firebase list for the input user (user_uid).
how should I manage an empty query to firebase?
thanks in advance!
getUserAppointmentsByDate(user_uid: string, start: string, end: string) {
if (typeof (user_uid) == "undefined" || typeof (start) == "undefined" || typeof (end) == "undefined") {
console.error("invalid argument for getPatientReport");
return;
}
return this.getUserAppointments(user_uid)
.map(
(appointment) => {
return appointment
.filter((appointment) => {
var appointmentStart = new Date(appointment.start);
var startFilter = new Date(start);
var endFilter = new Date(end);
//Filter old, not cancelled and not deleted
return (appointmentStart.getTime() < endFilter.getTime())
&& (appointmentStart.getTime() > startFilter.getTime())
&& (appointment.status != AppointmentStatus.CANCELLED);
});
})
}
getUserAppointments(user_uid: string): any {
return this.database.list('/appointment/users/' + user_uid) //*THIS IS AN EMPTY LIST
.mergeMap((appointments) => {
return Observable.forkJoin(appointments.map(
(appointment) => this.database.object('/appointment/list/' + appointment.$key)
.take(1)))
})
}
As the this.database.list('/appointment/users/' + user_uid) return a empty array. Observable.forkJoin(appointments.map( complete without emit any value (that is the expected way of forkJoin works). In this case, you have two options, handling in the complete function.
.subscribe(
res => console.log('I got values'),
err => console.log('I got errors'),
// do it whatever you want here
() => console.log('I complete with any values')
)
or handle in an if statement:
import { of } from 'rxjs/observable/of';
...
return this.database.list('/appointment/users/' + user_uid)
.mergeMap((appointments) => {
if (appointments.length === 0) return of([]);
return Observable.forkJoin(appointments.map(
(appointment) => this.database.object('/appointment/list/' + appointment.$key)
.take(1)))
})

Bound class method with with generic type

Here is a demo of the problem on tryflow
Essentially I have a class that operates on an array of gerically typed items.
type Props<ItemType> = {
items: ItemType[],
onSelect: (item: ItemType) => void
}
class List<ItemType> {
props: Props<ItemType>
activeIndex: number
constructor(props: Props<ItemType>) {
this.props = props;
this.activeIndex = 0;
}
getActiveItem() : ?ItemType {
return this.props.items[this.activeIndex];
}
submitItem(item: ?ItemType){
if(item) {
this.props.onSelect(item)
}
}
onClick() {
this.submitItem(this.getActiveItem())
}
}
let numbers: number[] = [1,2,3];
let onSelect = (value: number) => {};
let numberList: List<number> = new List({ items: numbers, onSelect: onSelect})
This example comes from a react component that I stripped down to more clearly demonstrate the problem.
It mostly works but ran into problems when I converted submitItem() to a bound method:
submitItem = (item: ?ItemType) => {
if(item) {
this.props.onSelect(item)
}
}
This causes the following error:
27: this.submitItem(this.getActiveItem())
^ Cannot call `this.submitItem` with `this.getActiveItem()` bound to `item` because `ItemType` [1] is incompatible with `ItemType` [2].
References:
8: class List<ItemType> {
^ [1]
20: submitItem = (item: ?ItemType) => {
^ [2]
The method needs to be bound to the class because it will be triggered as a callback from a DOM event.
How do I get the bound method to understand the generic type.
There appears to a problem there with property initialiser syntax (the recommended method of ensuring the method is bound to this) not creating the same type signature as when a regular class property is used. I've raised an issue with a simplified example.
However, in your example you don't seem to need to do this, as your onClick method is the one that needs to be bound and passed as the event handler
// ...
submitItem(item: ?ItemType): void {
if(item) {
this.props.onSelect(item)
}
}
onClick = () => {
this.submitItem(this.getActiveItem())
}
// ...

How to check for an element that may not exist using Cypress

I am writing a Cypress test to log in to a website. There are username and password fields and a Submit button. Mostly logins are straightforward, but sometimes a warning dialog appears first that has to be dismissed.
I tried this:
cy.get('#login-username').type('username');
cy.get('#login-password').type(`password{enter}`);
// Check for a possible warning dialog and dismiss it
if (cy.get('.warning')) {
cy.get('#warn-dialog-submit').click();
}
Which works fine, except that the test fails if the warning doesn't appear:
CypressError: Timed out retrying: Expected to find element: '.warning', but never found it.
Then I tried this, which fails because the warning doesn't appear fast enough, so Cypress.$ doesn't find anything:
cy.get('#login-username').type('username');
cy.get('#login-password').type(`password{enter}`);
// Check for a possible warning dialog and dismiss it
if (Cypress.$('.warning').length > 0) {
cy.get('#warn-dialog-submit').click();
}
What is the correct way to check for the existence of an element? I need something like cy.get() that doesn't complain if the element can't be found.
export function clickIfExist(element) {
cy.get('body').then((body) => {
if (body.find(element).length > 0) {
cy.get(element).click();
}
});
}
export const getEl = name => cy.get(`[data-cy="${name}"]`)
export const checkIfElementPresent = (visibleEl, text) => {
cy.document().then((doc) => {
if(doc.querySelectorAll(`[data-cy=${visibleEl}]`).length){
getEl(visibleEl).should('have.text', text)
return ;
}
getEl(visibleEl).should('not.exist')})}
I have done it with pure js.
cy.get('body').then((jqBodyWrapper) => {
if (jqBodyWrapper[0].querySelector('.pager-last a')) {
cy.get('.pager-last a').then(jqWrapper => {
// hardcoded due to similarities found on page
const splitLink = jqWrapper[0].href.split("2C");
AMOUNT_OF_PAGES_TO_BE_RETRIEVED = Number(splitLink[splitLink.length - 1]) + 1;
})
} else {
AMOUNT_OF_PAGES_TO_BE_RETRIEVED = 1;
}
});
I'm trying to check if element exists on body
cy.get('body').then((jqBodyWrapper) => {
With a pure js querySelector
if (jqBodyWrapper[0].querySelector('.pager-last a')) {
Then I fire my cy.get
cy.get('.pager-last a').then(jqWrapper => {
The hasClass() or for CSS selector has() is an inbuilt method in jQuery which checks whether the elements with the specified class name exists or not. You can then return a boolean to perform assertion control.
Cypress.Commands.add('isExistElement', selector => {
cy.get('body').then(($el) => {
if ($el.has(selector)) {
return true
} else {
return false
}
})
});
Then, it can be made into a special cypress method with TypeScript file (index.d.ts) file and can be in the form of a chainable.
declare namespace Cypress {
interface Chainable {
isExistElement(cssSelector: string): Cypress.Chainable<boolean>
}
}
As in the example below:
shouldSeeCreateTicketTab() {
cy.isExistElement(homePageSelector.createTicketTab).should("be.true");
}

Resources