i have one form with two inputs
context('Include contains from json file', function () {
beforeEach(() => {
cy.server()
cy.fixture("example.json")
.as('data')
.then((data) => {
cy.route('GET', 'example.json', data)
})
})
it('Výběr klienta', function () {
cy.visit('/info')
cy.get('[data-cy=username]').type(JSON.stringify(this.data)
cy.get('[data-cy=surname]').type(JSON.stringify(this.data)
})
})
How to type contains for two or more inputs from external file .json
My .json file
{
"name": "Jane"
"surname": "Doe"
}
The .json file should be in the fixtures folder as cypress will automatically search for test data inside this folder by default until and unless the path is specified otherwise.
You have to load the fixtures file in your tests in beforeEach() cy.fixture('example.json').as('data')
Then your code would be:
cy.get('[data-cy=username]').type(data.name)
cy.get('[data-cy=surname]').type(data.surname)
Works for me perfectly in single fixture JSON with multiple data and not stub API
before describe('Test Single Input Field Form', function() declare :
const testData = require("../../fixtures/multipleInputFields.json")
and then
`testData.forEach((data) => {
const message = data.message
it('Test Case', function(){
cy.log("data is:" + data)
cy.get('#user-message').type(message).should('have.value', message)
cy.get('#get-input > button').click()
cy.wait(200)
cy.get('span#display').should('have.text', message)
})
});`
Related
Context: I am trying to get Google Maps place data via the place_id on the beforeEnter() route guard. Essentially, I want the data to load when someone enters the url exactly www.example.com/place/{place_id}. Currently, everything works directly when I use my autocomplete input and then enter the route but it does not work when I directly access the url from a fresh tab. I've been able to solve this using the beforeEnter() route guard in traditional Vue, but cannot solve for this using Nuxt. Please help!
Question: How can I access the Vuex Store before a page loads in Nuxt?
Error: Any solution I try (see below) I either end up with a blank page or the page will not load (I think it is stuck in a loop and cannot resolve the Promise).
Attempted Solutions:
Using Middleware like below:
middleware({ store, params }) {
return store.dispatch('myModule/fetchLocation', params.id)
}
Using asyncData like below:
data(){
return{
filteredLocation: {}
}
}
// snip
async asyncData({ store, params }) {
const { data } = await store.dispatch('myModule/fetchLocation', params.id)
return filteredLocation = data
}
I tried looking into fetch, but apparently you no longer have access to context
Example Code:
In one of my store modules:
/* global google */
import Vue from 'vue'
import * as VueGoogleMaps from '~/node_modules/vue2-google-maps/src/main'
Vue.use(VueGoogleMaps, {
load: {
key: process.env.VUE_APP_GMAP_KEY,
libraries: 'geometry,drawing,places'
}
})
export const state = () => ({
selectedLocation: {}
})
export const actions = {
fetchLocation({ commit }, params) {
return new Promise((resolve) => {
Vue.$gmapApiPromiseLazy().then(() => {
const request = {
placeId: params,
fields: [
'name',
'rating',
'formatted_phone_number',
'geometry',
'place_id',
'website',
'review',
'user_ratings_total',
'photo',
'vicinity',
'price_level'
]
}
const service = new google.maps.places.PlacesService(
document.createElement('div')
)
service.getDetails(request, function(place, status) {
if (status === 'OK') {
commit('SET_PLACE', place)
resolve()
}
})
})
})
}
}
export const mutations = {
SET_PLACE: (state, selection) => {
state.selectedInstructor = selection
}
}
EDIT: I already have it in a plugin named google-maps.js and in my nuxt.config.js file I have:
plugins: [
{ src: '~/plugins/google-maps.js' }
]
//
//
build: {
transpile: [/^vue2-google-maps.js($|\/)/],
extend(config, ctx) {}
}
Using Middleware is how we can access Vuex before page loads. try putting the configuration part in a custom Nuxt plugin.
Create a file in Plugins folder (you can name it global.js).
Put this
import Vue from 'vue'
import * as VueGoogleMaps from '~/node_modules/vue2-google-maps/src/main'
Vue.use(VueGoogleMaps, {
load: {
key: process.env.VUE_APP_GMAP_KEY,
libraries: 'geometry,drawing,places'
}
})
in global.js.
Then add the plugin in nuxt.config.js like this.
plugins: [
'~/plugins/global.js'
]
Also, make sure you're using underscore before 'page_id' name in your folder structure.
I got some json data in a local file the file is .txt file and the data is not directly accessible so I just changed the file format to .json and after that, I tried to get clean data to loop through with the code below.
I'm getting the data via computed in this component but I want to set this clean data as a prop to a child component.
I want to create many child components with clean data.
Thank you very much in advance!
Code:
<script>
export default {
name: 'Dashboard',
components : {
'my-table': mytable,
'my-search': search,
},
data: function() {
return {
casesDataList: [],
};
},
computed:{
ClearList: function(){
var casesDataList = this.casesDataList.map(function (neo){
return {ID: neo.Attributes[1].Value, Date: neo.FormattedValues[0].Value, Owner: neo.FormattedValues[1].Value};
});
return casesDataList;
}
},
created: function(){
this.getCasesData();
},
methods: {
getCasesData() {
fetch("Weather.json")
.then(response => response.json())
.then(data => (this.casesDataList = data.Entities));
},
}
};
</script>
You can pass the computed as a prop to the child directly:
<child :propname="ClearList"></child>
In the child:
export default {
props: ['propname'],
// ...
}
I have the following json file. Right now, i have kept this in my ReactJS project itself locally. Later on planning to move in a server location.
abtestconfig.json
[
{
"abtestname": "expAButton",
"traffic": 1,
"slices":
[
"orange",
"blue"
]
},
{
"abtestname": "expTextArea",
"traffic": 0.5,
"slices":
[
"lightgrey",
"yellow"
]
}
]
I want to read and get data and parse it and apply in a function. I got some reference sample code and trying to use fetch api to react json file with the following code.
After reading this json file, i will have to pass the data in abtest function, as you can see now it's sending with hard coded value abtest('expAButton', 0.75).slices('orange', 'blue').run(function ()
I have the following doubts and wanted to get your guidance / clarification.
1. Is it correct way to read json file using fetch api? Is there any other best approach?
2. When I use fetch api like mentioned below, console log displays GET http://localhost:8080/abtesting/abtestconfig.json 404 (Not Found)
app.jsx file:
import './abtesting/abtestconfig.json';
class App extends React.Component {
constructor() {
super();
this.onClick = this.handleClick.bind(this);
this.onClickNewUser = this.handleNewUser.bind(this);
this.state = {
bgColor: '',
data: []
}
};
handleNewUser (event) {
abtest.clear();
window.location.reload();
}
render() {
return (
<Helmet
/>
<p><b>A/B Testing Experience</b></p>
<div className="DottedBox">
<p><button id = "newUserButton" onClick = {this.onClickNewUser} style={{backgroundColor:"red"}}>Welcome and click here</button></p>
</div>
);
}
handleClick () {
abtest('expAButton', 0.75).slices('orange', 'blue').run(function () {
expAButton.style.backgroundColor = this.slice.name;
});
}
setStyle (stylecolor) {
this.setState({
bgColor: stylecolor
})
}
componentDidMount () {
this.handleClick();
fetch('./abtesting/abtestconfig.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
}
}
export default hot(module)(App);
I am trying to convert a table to JSON, to search for data easily, the URL is: http://www.tppcrpg.net/rarity.html
I found this package:
https://www.npmjs.com/package/tabletojson
I tried to use it like:
'use strict';
const tabletojson = require('tabletojson');
tabletojson.convertUrl(
'http://www.tppcrpg.net/rarity.html',
{ useFirstRowForHeadings: true },
function(tablesAsJson) {
console.log(tablesAsJson[1]);
}
);
However it returns undefined in the console, are there any alternative options or am I using the package wrong?
Hey you are actually getting data, change the console.log
Your output have total one array only but you are putting tablesAsJson[1] in console, but array index starts with [0].
'use strict';
const tabletojson = require('tabletojson');
tabletojson.convertUrl(
'http://www.tppcrpg.net/rarity.html',
function(tablesAsJson) {
console.log(tablesAsJson[0]);
}
);
For better looking code:
const url = 'http://www.tppcrpg.net/rarity.html';
tabletojson.convertUrl(url)
.then((data) => {
console.log(data[0]);
})
.catch((err) => {
console.log('err', err);
}); // to catch error
I'm trying to convert a TSV file into JSON and write it to disk using text2json.
Input data
There is an empty line at the end
U+2B695 shī
U+2B699 pū
U+2B6DB zhī
U+2B6DE jué
U+2B6E2 níng
U+2B6F6 chì
U+2B6F8 tí
Test
I've this test running with ava
import fs from "fs";
import test from "ava";
import jsonfile from "jsonfile";
import dataminer from "../src/dataminer";
test("extractPronunciation()", t => {
const filepath = "src/codepoint-ruby.tsv";
const data = dataminer.convertToJson(filepath, { separator: " " });
t.is(data > 0);
});
Code
And this method based on text2json:
import jsonfile from "jsonfile";
import text2json from "text2json";
export default {
convertToJson: (filepath, options) => {
const data = [];
const parse = new text2json.Parser({ ...options, hasHeader: true });
parse
.text2json(filepath)
.on("row", row => {
data.push(row);
})
.on("end", () => {
console.log("Done >>>>>");
return data;
});
},
};
Question
I see not trace of the end event being triggered, and the convertToJson() return nothing so my test fail, am I missing something?
In your approach, you're filling the data array by reading asynchronously from a stream, instead of putting the whole file in memory and doing it synchronously. (And that's why you've got to use the on event to push data to your array).
This means that, in the same way you use
parse.text2json(filepath).on("row", row => {
data.push(row);
});
you also need to use an end event to log the final result
parse.text2json(filepath)
.on("row", row => {
data.push(row);
})
.on('end', () => {
console.log(data)
});