How to test a component when a new item is displayed in Vue?
Do you have any idea how can I test a Vue component if it actually pass, display a new item?
For example, I have a component that has a form that contains:
Title text field
Content text field
How can I test this component if it displays the newly added data using jest?
See also questions close to this topic
-
Can I access any response that is shown in dev tools?
Here is the scenario...
- I have an Iframe that is using RightSignature to capture a signed document.
- When I submit the document in the iframe, I can see in my Dev tools that I have a PUT with a json response that I want to grab.
- once it is submitted, the page in the iframe is redirected.
So far I have had no luck in capturing the response using just vanilla js and .addEventListener. It seems like there should be a way to do it but I am just curious if what I think should be possible actually is.
So in short, if I can see the response in my Dev Tools, does that mean I should be able to capture it somehow using js, or because it is in an iframe does that not necessarily translate into something that is accessible to me? I just want to know so I dont keep trying to go down a path that leads nowhere.
Thanks
-
Is there is a way to DM someone that is mentioned in a message with discord.js?
Is there is a way to DM someone that is mentioned in a message with discord.js?
this is my code.
client.on("message", message => { if (message.author.bot) {return} let person = message.content.mentions person.send("My message") })
it's not working for some reason
-
How to check cookie parameters in if-else condition after it is stored?
I have here a function that checks each parameters in the url and store it as cookie. But I have a problem, whenever I pass those parameter entered into a new url using
XMLHttpRequest()
it returns only the first parameter entered from the user. I guess this is something to do with theif-else
condition in mycode.Here is my javascript code:
<!-- Get Parameters for gclid, token , fbclid or cjevent when user visits the website --> <script> window.onload = function() { try { var url_string = (window.location.href).toLowerCase(); var url = new URL(url_string); // check parameters if exists ['gclid', 'token', 'fbclid', 'cjevent'].forEach(function (key) { var value = url.searchParams.get(key); if (value) { //token expires in 6 hours document.cookie = `${key}=${value}; max-age=21600` + ';path=/'; } }); const getCookieValue = (name) => ( document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || '' ) // Sending a get request to laravel controller var base_url = window.location.origin; // get the base url var params = ''; // pass parameters if gclid, token, or fbclid if(getCookieValue('gclid')) { params = 'gclid=' + getCookieValue('gclid');} else if (getCookieValue('token')) { params = 'token=' + getCookieValue('token');} else if (getCookieValue('fbclid')) { params = 'fbclid=' + getCookieValue('fbclid');} else if (getCookieValue('cjevent')) { params = 'cjevent=' + getCookieValue('cjevent');} // send those parameters in TrafficTracking Controller storeTracking function let xhr = new XMLHttpRequest(); xhr.open("GET", base_url+"/storetrackvisit?"+params, true); xhr.send(); } catch (err) { console.log("Issues with Parsing URL Parameter's - " + err); } } </script>
When I try to use the
alert(params)
function in the varparams
it returns only the first parameter that user has entered.For example:
1.) User enters
test.com?gclid=111
-> stores that as a cookie2.) user re enters another value for other parameter
test.com?token=551
-> it will still alert thegclid
parameterHow do I refactor my if-else condition that returns only the parameter when a user enters it and assign it in the
params
variable. So that the variableparams
is dynamic when passing it to the new urlXMLHttpRequest()
.I believe this is something to do with this code:
if(getCookieValue('gclid')) { params = 'gclid=' + getCookieValue('gclid');} else if (getCookieValue('token')) { params = 'token=' + getCookieValue('token');} else if (getCookieValue('fbclid')) { params = 'fbclid=' + getCookieValue('fbclid');} else if (getCookieValue('cjevent')) { params = 'cjevent=' + getCookieValue('cjevent');} alert(params);
How can I modify my if-else conditions to return only the parameters what user entered? I believe that what I've done it fetches the last cookie saved. Is there anything good to do about the
if/else
condition? -
How to mock Currency Singleton Object
For Unit Test, I am trying to mock the getInstance method in currency class java
whenever(getCurrency).thenReturn(Currency.getInstance("USD"))
But this is not working
-
unable to see the updated DOM in spec after its getting modified
I am writing a functional spec using Mocha/JSDOM and asserting with 'chai'.
The use case is when I call the function: updateContent,
- It would internally call another function that would fetch some HTML content.
- Later I would process that HTML content and add it to the existing DOM elements.
This is working fine when I run on the server but the issue is when I try to write a spec, not able to see the updated DOM. I checked the updateContent function by placing the console statement and I see the updated content but once the control transferred to the spec function, I am seeing the original DOM that is added to JSDOM.
This is written using Typescript, js combination, and JQuery for DOM operations
Could you please help me with what am I missing here? Any suggestion/info would be helpful. I tried using global while accessing
updateContent function available in helper.js file
function updateContent(year, fetchAge) { Promise.all([fetchAge("age")]).then((data) => { console.log("DOM before update ="+$('html').html()); data = data[0].replace(/{{age}}/g, year); $('.mybenifits .content').html(data); console.log("DOM after update ="+$('html').html());//Able to see the updated DOM console.log("$('.mybenifits .content').html="+global.$('.mybenifits .content').html()); }).catch((error) => { console.log(" ******* Error while fetching age info"); }); }
Spec Code snippet: helper.test.js
const expect = require('chai').expect; const assert = require('chai').assert; const sinon = require('sinon'); const { JSDOM } = require('jsdom'); const { updateContent } = require('../../main/webpack/common/helper.js'); describe('Helper - Example', () => { it('should update the content', () => { let htmlStr = '<!doctype html><html><body><div class="mybenifits"><div class="content"></div></div></body></html>'; const jsdom = new JSDOM(htmlStr, { url: 'http://localhost/', }); //Setting Global variables - start global.window = jsdom.window; global.document = jsdom.window.document; global.$ = require('jquery'); //Setting GLobal variables - end //Mocking fetchAge function function fetchAge(featurename) { return '<p id="fcontent">Current Age is {{age}}</p>'; } updateContent("2020",fetchAge); console.log("Total html file ="+$('html').html()); //expect($('.mybenifits .content').html()).to.be.equal('<p id="fcontent">Current Age is 2020</p>'); //expect(global.$('.mybenifits .content').html()).to.be.equal('<p id="fcontent">Current Age is 2020</p>');//Not working even if I use global }); });
-
Testing Controller and Service in Jest
I'm fairly new to Jest and have been trying (with no luck) to figure out how to write tests for my controller. I'm not sure how to write the test as it calls another function. It would be great if I could get pointed in the right direction at least. Thanks in advance.
controller.ts
import * as Services from './services'; export async function GetCountriesList(req: Request, res: Response): Promise<void> { const response = await Services.GetCountriesList(); res.status(response.code).json({ status: response.status, message: response.message, count: response.count, data: response.data }); }
service.ts
import db from '../../modules/db'; import { DBGenericDataResponse } from '../../types/models'; export async function GetCountriesList(): Promise<DBGenericDataResponse> { const lQuery = 'somquery'; const responseMessage: DBGenericDataResponse = { code: 200, status: 'ok', message: '', count: 0, data: [], error: '' }; try { const dbResult = await db.query<any>(lQuery); responseMessage.message = 'Countries returned'; responseMessage.count = dbResult.rows.length; responseMessage.data = dbResult.rows; } catch (err) { responseMessage.code = 400; responseMessage.status = 'error'; responseMessage.message = 'Error retrieving Countries List'; responseMessage.error = err; } return responseMessage; }
-
Vue.js / Vuetify How to replace id into object (found on the basis of this id)
I am using vue,vuex,vuetify. I have two collections on my MongoDB, pigeons and dovecotes. Dovecotes are containers for pigeons, it has a variable which is an array of pigeons. The pigeon has a variable which is the id of the dovecote to which it is assigned.
I want to show the pigeons on my table, it's easy to get but on column dovecote is a ID of dovecote to which it is assigned.
I want change it into this dovecote name.
Summarizing:
-I have a table of pigeons -I have a table of dovecotes
I want to show a table where id will be represented by the name of the object that will be searched for based on that id.
please help, I'm just learning, and I'm stuck in this place :(
-
What is the best practice to get the required data into VueJS component?
I'm building my first VueJS application which is intended to be used by hundreds of people in the future. I tried to make the individual components reusable and indpendent as possible. To achieve this i decided to let every component fetch its required data themselves. This works fine but i'm not sure if its best practice. I could also pass the data between the components or even using the 2-way data binding functionality.
The sketch bellow describes one of the situations i have. Note that
1 account has 1..* users
. As you can see i need to fetch theaccounts
to display them in theaccountOverviewComponent
.- Currently i only fetch the
accounts
in theaccountOverviewComponent
and fetch the users when theaccount edit button
by the passedaccountId
in theaccountOverviewComponent
is clicked. This way i don't fetch data i don't need at the time. - I can also include the
users
(god knows which data/relations will be added in future) to thefetch account
response as wel so i can pass all required data to theaccountShowComponent
when aaccount edit button
is clicked. This way i can save requests to the server with the side note that i fetchusers
ofaccounts
i dont need. A possible disadvantage is that theaccount
is updated in theaccountShowComponent
and not in theaccountOverviewComponent
(for example when theaccountShowComponent
is amodal
on top of theaccountOverviewComponent
. So i need to pass the updatetaccount
back or re-fetch the accounts after a save or something. - As third option I can do the same in option 2 but than with the 2-way data binding which handles the data synchronization between the components. This will probably restrict the usage of the
accountShowComponent
to cases where theaccountShowComponent
is used "on top" of a parent which contains the data. - I can also store the data in a
Vuex
store and update the stores all the time. I read that this is bad practive as it should be only used for data which is required accros the SPA. I thinkVuex
is overkill in "simple" situations like this?
What is the best practice of the described situation? I have a bunch of comparable situations/scenarios in my application. Performance (also for mobile devices), scalability and being "future proof" (extendability/modularity) are important for me. Can someone help me out because i'm a bit lost in the options i have?
UPDATE
The reason i think Vue is overkill is comming from this article which makes totally sense from a software engineer perspective to me (i may be wrong). As my components have a kind of "parent - child" relation so i can solve my "issue" easily with passing data (or use 2-way data binding) and callback-events.
The number one use case for storing data in a centralized store like Vuex, is, because the data must be accessible in multiple places of your application, by components which oftentimes are not related in any way (they neither are parents or children of each other). An example of this would be certain user settings to configure how your application looks or what date format should be used, to name a concrete example.
- Currently i only fetch the
-
dynamic routing with vue router in vue js with strapi headless CMS - router link and a href tags throwing errors
I'm building out a strapi site with vue js.
In strapi, I have a custom collection type called "webinars" - the endpoint to hit that looks like this:
const response = await axios.get('http://localhost:1337/webinars')
The above returns a JSON object.
To hit individual webinars, each one has a unique identifier, starting at 1. to hit the individual webinar JSON data that looks something like this:
const response = await axios.get('http://localhost:1337/webinars/1')
Which would return a particular webinar.
I need 2 views, one is all of the webinars, and specific ones.
So to start, please see my router below:
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Webinars from '../views/Webinars.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/webinars', name: 'Webinars', component: Webinars }, { path: '/webinars/:id', name: 'Webinars', component: WebinarSingle } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
Now, my view that returns all the webinars looks like this:
<template> <div> <h1>{{ header }}</h1> <div v-if="error" class="webinar-error"> <h1>{{ error }}</h1> </div> <div v-else> <div class="webinar-card" v-for="webinar in webinars" :key="webinar.id"> <h3>{{ webinar.webinar_title }}</h3> <p>{{ webinar.webinar_description }}</p> </div> </div> </div> </template> <script> import axios from 'axios'; export default { name: 'Webinars', data () { return { webinars: [], error: null } }, async mounted () { try { const response = await axios.get('http://localhost:1337/webinars') this.webinars = response.data } catch (error) { this.error = error; } }, props: { header: String } } </script>
What I need to do is create a view that renders when you hit a webinar particular ID ('http://localhost:1337/webinars/1', 'http://localhost:1337/webinars/2' etc)
My understanding is I need to use dynamic routes. So I modified my router and added the import statement that pulls in the view, as well as adding the declaration:
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Webinars from '../views/Webinars.vue' import WebinarSingle from '../views/WebinarSingle.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/webinars', name: 'Webinars', component: Webinars }, { path: '/webinars/:id', name: 'Webinars', component: WebinarSingle } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
I think the next step here is to now add in
<router-link>
tags to hit that webinar based on ID. https://router.vuejs.org/api/is the component for enabling user navigation in a router-enabled app. The target location is specified with the to prop. It renders as an tag with correct href by default, but can be configured with the tag prop. In addition, the link automatically gets an active CSS class when the target route is active.
is preferred over hard-coded for the following reasons:
It works the same way in both HTML5 history mode and hash mode, so if you ever decide to switch mode, or when the router falls back to hash mode in IE9, nothing needs to be changed. In HTML5 history mode, router-link will intercept the click event so that the browser doesn't try to reload the page. When you are using the base option in HTML5 history mode, you don't need to include it in to prop's URLs.
So I go ahead and attempt to add them into the webinars component:
<template> <div> <h1>{{ header }}</h1> <div v-if="error" class="webinar-error"> <h1>{{ error }}</h1> </div> <div v-else> <div class="webinar-card" v-for="webinar in webinars" :key="webinar.id"> <router-link to="/webinars/{{ webinar.id }}"> <h3>{{ webinar.webinar_title }}</h3> <p>{{ webinar.webinar_description }}</p> </router-link> </div> </div> </div> </template>
This returns:
Module Error (from ./node_modules/vue-loader/lib/loaders/templateLoader.js): (Emitted value instead of an instance of Error)
Errors compiling template:
to="/webinars/{{ webinar.id }}": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of , use .
So I change it to:
<template> <div> <h1>{{ header }}</h1> <div v-if="error" class="webinar-error"> <h1>{{ error }}</h1> </div> <div v-else> <div class="webinar-card" v-for="webinar in webinars" :key="webinar.id"> <router-link :to="/webinars/{{ webinar.id }}"> <h3>{{ webinar.webinar_title }}</h3> <p>{{ webinar.webinar_description }}</p> </router-link> </div> </div> </div> </template>
I then get:
error in ./src/components/Webinars.vue?vue&type=template&id=44d01bf9&
Syntax Error: Unexpected token (1:301)
What is the unexpected token?
How do you map dynamic routes in vue js to different endpoints?
-
Jest mock middleware response
I am trying to mock a middleware response, and i am trying to use
jest.spyOn()
but can't seem to get it workingMy controller.ts has the following
import someMiddleware from '../someMiddleware; .... .... this.route.post('/getData', someMiddleware, setValue)
In someMiddlware.ts
//making a fetch call based on data in req.body ..... const data = await fetchData(url, data) next() .....
In my test file controller.test.ts
describe('Test Data', () => { beforeEach(() => { someMiddlewareSpyOn = jest.spyOn(meddelware, "someMiddleware"); }); afterEach(() => { jest.resetModules(); jest.resetAllMocks(); }); it('response status should be a 200', async () => { someMiddlewareSpyOn.mockResolvedValue({data:[].....}); const res = await request(app.getServer()) .post('/getData'); expect(res.status).toBe(200); }) });
The above does not work, looking for assistance on how to do this.
-
Warning: <TEXT /> is using incorrect casing
console.error node_modules/react-dom/cjs/react-dom.development.js
Warning:
<TEXT />
is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.I have the issue with Jest and react-pdf
In the component where I'm using the react-pdf components this is written as:
<Text>
, but when performing the test it's appearing as<TEXT>
My component:
const HeaderPDF: React.FC<Props> = (props: Props) => { return ( <View style={styles.headerContainer} fixed> <View style={styles.headerTop}> <Text style={styles.textBoldTopHeader}> "Some text" </Text> <View style={styles.headerTopInputContainer}> <View style={styles.headerTopInputTextContainer}> <Text style={styles.textInputTopHeader}>Route</Text> </View> <View style={styles.inputSmall} /> </View> </View> </View> ); };
The test:
import React from 'react'; import { render } from 'tests/support/customRender'; import HeaderPDF from ../../HeaderPDF'; describe('HeaderPDF', () => { it('Renders a HeaderPDF component successfully', () => { const { container } = render( <HeaderPDF someProps /> ); expect(container).toMatchSnapshot(); }); });