Each key must be a number of string; got undefined protractor - javascript

I am trying to read data from json file but I have some trouble.
How can I get items from a json file to individual items?
My json file:
[
{
"UserName": "test#test.en",
"Password": "tests123"
}
]
My method:
element(by.name('username')).sendKeys(browser.params.UserName);
element(by.name('password')).sendKeys(browser.params.Password);
as a result i get
Failed: each key must be a number of string; got undefined

You are passing an array of object and not an object, thus, you have to be precise in your variable.
Either directly pass an object
{
"UserName": "test#test.en",
"Password": "tests123"
}
Or specify the index in the array
element(by.name('username')).sendKeys(browser.params[0].UserName);
element(by.name('password')).sendKeys(browser.params[0].Password);

My Test was also failing with json file then i converted my datafile into ts file like below
export const DataForSearch =
{
Login:
{
CorrectCreds: { username: 'test#test.en', password: 'tests123' }
}
};
then use this in my test case like
import {DataForSearch } from "../DataLogin"
const using = require("jasmine-data-provider");
describe("Login Page", () => {
using(DataForSearch.Login, (data: any, alldesc: any) => {
it("Login", () => {
element(by.name('username')).sendKeys(data.username);
element(by.name('password')).sendKeys(data.password);
})
})
})
you can try typescript file, if you still facing issue.If you face any issue let me know

Related

Cannot Firebase downloaded Url?

I have a Service TypeScript File with following Code
export class FirebaseService {
constructor(private afs: AngularFirestore, private storage: AngularFireStorage) {}
uploadFile(file: any) {
const filePath = 'path/to/save/file';
const fileRef = this.storage.ref(filePath);
const task = this.storage.upload(filePath, file);
return task.snapshotChanges().pipe(
finalize(() => {
return fileRef.getDownloadURL()
})
).toPromise();
}
createDocument(collection: string, name: string, file: any) {
this.uploadFile(file).then(downloadURL => {
if (downloadURL) {
const data = {
title: name,
downloadURL: downloadURL
};
this.afs.collection(collection).add(data);
} else {
console.log("downloadURL is not defined.");
}
});
}
}
In my Component I have following code
export class CreatePage implements OnInit {
name = ""
file: any;
onFileChanged(event: any) {
this.file = event.target.files[0];
}
onSubmit() {
console.log("this.selectedOption = ",JSON.stringify(this.selectedOption))
console.log("this.name = ",JSON.stringify(this.name,))
console.log("this.file = ",JSON.stringify(this.file))
console.log("TEST", this.file)
this.firebaseService.createDocument(this.selectedOption, this.name, this.file)
this.name = "", this.selectedOption = ""
}
}
The output of the 4 values from console log is:
Selected option: freunde
this.selectedOption = "freunde"
this.name = "test"
this.file = {}
TEST File {name: 'berge.jpg', lastModified: 1673618629595, lastModifiedDate: Fri Jan 13 2023 15:03:49 GMT+0100 (Mitteleuropäische Normalzeit), webkitRelativePath: '', size: 990092, …}
Selected option:
The HTML looks like this:
<ion-item> <input type="file" (change)="onFileChanged($event)"> </ion-item>
How can I fix this problem? The error message says following:
core.mjs:9095 ERROR Error: Uncaught (in promise): FirebaseError: [code=invalid-argument]: Function addDoc() called with invalid data. Unsupported field value: undefined (found in field downloadURL.metadata.cacheControl in document freunde/lcAwFcHvQSo5iV6ExQPi)
It will upload the image to the storage, but not the downloaded url in the firebase firestore. Can someone help me please?
The Object look like this after printing the data object
data = {
"title": "test",
"downloadURL": {
"source": {
"source": {
"source": {}
}
}
}
}
Debugging step 1.
Make your code show exactly what you are sending to Firebase. Change the console.log to three console.logs
console.log("this.selectedOption = ",JSON.stringify(this.selectedOption,null,2))
console.log("this.name = ",JSON.stringify(this.name,null,2))
console.log("this.file = ",JSON.stringify(this.file,null,2))
Also add this before your call to add:
Before this:
this.afs.collection(collection).add(data);
Add this:
console.log("data = ", JSON.stringify(data, null, 2))
Show in your question the exact output from the above
This will maximise our chances of finding the problem.
Why JSON.stringify?
I can see by your comment that you are annoyed by my suggestion to use JSON.stringify. The reason to use it is to force the console.log output to be the instantaneous value of the variable at that time, rather than an automatically-updating value that might display a different value on the console than the value being experienced by your program at the time of the error.
You can now see the utility of the JSON.stringify!
Your simple console.log(this.file) is reporting the full value with properties filled in.
But the JSON stringify, is showing you that, at the time that the line was run, this.file was simply {}, i.e. an empty object. Firebase was being sent {}, not the filled-in object.
You can also see the value of the ,null,2
This would have prevented the truncation of a line at:
size: 990092, ...
Volunteers on Stack Overflow would therefore have been able to tell if there was something later on in the object that was undefined or in some other way conflicting with Firebase.
These debugging tips are there to help us help you. If you don't follow the advice we give, it lessens people's enthusiasm to help.
I have now fixed my problem with following code.
I changed the uploadFile Function to following:
uploadFile(file: any) {
const filePath = 'images/file';
const fileRef = this.storage.ref(filePath);
const task = this.storage.upload(filePath, file);
return task.snapshotChanges().toPromise().then(() => {
return fileRef.getDownloadURL().toPromise()
});
}
Instead of returning a object I return now a Promise. This way we are waiting for the promise to resolve and getting the downloadURL. It should resolve the issue and allow the createDocument method to access the download URL without any error.

How to resolve a GraphQL DateTime field receiving '0000-00-00' and throwing error?

I have a similar to this question, however I don't see how it could be resolved using this other syntax currently in my Apollo project.
The issue is '0000-00-00' values coming from SQL db to my Apollo GraphQL server, thus throwing errors of invalid DateTime type. I'd like to write a resolver for the datetime field in question, like:
import gqlDate from 'graphql-iso-date';
const MyType = new gql.GraphQLObjectType({
name: 'Type',
description: 'This is a GraphQL type.',
fields: () => {
return {
datetime: {
type: gqlDate.GraphQLDateTime,
description: 'The datetime field of my type.',
resolve: (record) => {
return record === '0000-00-00 00:00:00' ? null : record;
}
}
};
}
});
However I cannot adjust this example to this other syntax my project is setup to:
import { gql } from 'apollo-server'
export const schema = gql`
extend type Query {
users(id: ID): [User!]
}
type User {
id: ID!
first_name: String!
middle_name: String
birthday: String!
}
import graphqlFields from 'graphql-fields'
export const usersResolver = {
Query: {
users: async (_, params, context, info) => {
const requestedColumns = Object.keys(graphqlFields(info))
return context.dataSources.db.getUsers(params, requestedColumns)
},
},
}
I played around with adding something like this to the resolver, but I'm not sure if it's the right thing to do and how exactly to implement it. Since the field resolves to Scalar, my guess is the below code won't be reached.
birthday: (parent, params, context, info) => { ... },
I also tried adding a separate query for the field, but am not sure how to connect it to the original users one.
My final resort is to just query the birthday as String and handle it on the front end, but that seems to be totally inappropriate compared to resolving it in GraphQL.

Jest typescript check for type

lets say i have the following interface:
export interface CMSData {
id: number;
url: string;
htmlTag: string;
importJSComponent: string;
componentData: ComponentAttribute[];
}
Then i have a method that returns an array of this object type:
public async GetContent(url: string): Promise<CMSData[]>{
const response = await super.get<ICMSContentData[]>(url, {});
try {
if (response?.parsedBody) {
return this.ProcessResponse(response.parsedBody);
} else {
this.handleHTTPError(new Error("Error"));
return [];
}
} catch (e) {
this.handleHTTPError(e);
return [];
}
}
Then i want to test that this is the case so i write the following test:
import {ContentIOService} from "..";
import {CMSData} from "../IOServices/ContentIOService";
require('es6-promise').polyfill();
require('isomorphic-fetch');
test('Get Content', async () => {
const service = ContentIOService.getInstance();
const data = await service.GetContent("https://1c7207fb14fd3b428c70cc406f0c27d9.m.pipedream.net");
console.log(data)
expect(data).toBeInstanceOf(CMSData[]);
});
However here i get the following error:
'CMSData' only refers to a type, but is being used as a value here.
So how can i test that the data i get back is valid and of the right type?
If the type you're looking for is a call, the .toBeInstanceOf(Class) method accepts a parameter which MUST BE a JavaScript class constructor instead of TS type.
You should let TSC check whether you receive the correct type of data at compile time. Code written inside test suites and test cases is executed at runtime, .toBeInstanceOf(Class) is a runtime check, NOT compiler time.
At runtime, you may want to use expect.objectContaining(object) matches any received object that recursively matches the expected properties.

Send an enum to graphql API from react app

I have an input (attached image) that I need to send to the graphql api from react application.
I am using below code to send this object and enum with init to graphql api
Reactjs Code
const RequestActionEnum = {
NEW: 'New',
UPDATE: 'Update',
ARCHIVE: 'Archive'
}
LocalCodeMutation({
variables: {
data: {
id: null,
city: values.jurisdiction,
country: values.country,
description: values.description,
edition: values.edition,
name: values.codeName,
note: 'test',
requestType: RequestActionEnum.NEW, // this is where i am sending enum value to api
state: values.state
}
}
});
Below code is where I am calling the mutation
const [LocalCodeMutation] = useMutation(LOCALCODE_MUTATION, {
refetchQueries: () => [
{ query: GET_LOCALCODES },
],
});
export const LOCALCODE_MUTATION = gql`
mutation LocalCodeMutation($data: LocalCodeRequestParamsInput) {
localCodeMutation(data: $data) {
ok
errors
localCodeInsertedId
}
}
`;
I am getting this error when I send to the API:
Error: GraphQL error: Variable $data got invalid value.
How can I send enum value to graphQL api from react component.
Could any one please suggest any ideas on this?
The enum values for RequestActionEnum are
NEW
UPDATE
ARCHIVE
If you were using this enum as a literal (not a variable), you would write it like this:
{
someField(someArgument: NEW)
}
Similarly, if you're using variables, you would use "NEW". Instead, you're using "New", which is not a valid enum value for this particular enum.
FWIW, if you actually read through to the end of the error, it would tell you as much as well.

Using Variables with react-apollo Query

I've attached a query to my React Native component like so:
let getNearbyStoriesQuery = gql`{
getStoriesNearbyByGeoHash(geoHash: "8k"){
id
}
}`;
export default graphql(getNearbyStoriesQuery,
{
props: (props) => {
debugger;
let storiesNearby = props.data.getStoriesNearbyByGeoHash.map((story) => {
return {
id: story.id,
}
});
return {storiesNearby};
},
variables: {
geoHash: mockGeoHash
}
})(Home); // Home is the React Native Component
I'm able to retrieve data from using this technique as long as I hardcode a value in for geoHash in the query; in this case I used "8k". However, when I attempt to modify the query so that I can puss in a variable like so:
let getNearbyStoriesQuery = gql`{
getStoriesNearbyByGeoHash($geoHash: String!){
id
}
}`;
I get an error saying Expected Name, found $. This method of passing variables to queries is repeated across multiple sources. What am I doing wrong here?
Should be:
query GetStoriesNearbyByGeoHash($geoHash: String!) {
getStoriesNearbyByGeoHash(geoHash: $geoHash){
id
}
}
Have a look on how to use variables in graphql: http://graphql.org/learn/queries/#variables

Categories

Resources