vue3 filtered data on computed with chartjs - chart.js

im learning about vuejs 3 and for example i want to show a chartjs with a combo to filter data. (Without the combo, everything works correctly)
i have a parent component chartjs.vue where import the chartjs and the combo. when i select a year, i change the variable and show it on the template
<script setup>
import ChartJsBarChart from '#/views/charts/chartjs/ChartJsBarChart.vue'
import SelectYear from '#/componentes/selectYear.vue'
const api = ref('exp')
const year = ref([])
function selectYear(x) {
year.value = x
}
</script>
<template>
<!-- 👉 Latest Statistics -->
<VCol cols="24" md="12">
<VCard>
<VCardItem class="d-flex flex-wrap justify-space-between gap-4">
<VCardTitle>Choose a year</VCardTitle>
</VCardItem>
<VCardText>
<SelectAno #input="selectAYear" />
</VCardText>
</VCard>
</VCol>
<VCol cols="24" md="12">
<VCard>
<VCardItem class="d-flex flex-wrap justify-space-between gap-4">
<VCardTitle>Total</VCardTitle>
</VCardItem>
<VCardText>
<ChartJsBarChart :yearSelected="year" :url="api" />
</VCardText>
</VCard>
</VCol>
</template>
one child component with a select (to try props and emit) selectYear.vue
<script setup>
import { ref, defineEmits, watch } from 'vue'
const emit = defineEmits(['input'])
let selected = ref([])
const years = [
'2005',
'2008',
'2009',
'2010',
'2011',
'2012',
'2014',
'2015',
'2016',
'2017',
'2018',
'2019',
'2020',
'2021',
'2022',
'2023',
]
watch(
() => selected.value,
(newValue, oldValue) => {
change(newValue)
},
)
const change = val => emit('input', val)
</script>
<template>
<VSelect
v-model="selected"
:items="years"
label="choose a year"
/>
</template>
and last child component with the chartjs ChartJsBarChart.vue
<script setup>
import BarChart from '#/libs/chartjs/components/BarChart'
import axios from '#axios'
import { ref, onMounted, computed } from "vue"
import { useStatesStore } from '#/store/states'
const props = defineProps({
url: {
type: null,
required: true,
},
yearSelected: {
type: null,
required: true,
},
})
const apiData = ref([]) //data from API
const data = ref({}) // data parsed to chartjs
const store = useStatesStore()
const states = ref(store.states) // legend
const filterByYear = computed(() => {
return apiData.value.filter(item => item.year === '2005')
})
onMounted(async () => {
await axios
.get('/api/dashboard/expProvActiv')
.then(res => {
apiData.value = res.data['hydra:member']
})
})
</script>
<template>
{{ props.yearSelected }}
<hr>
{{ apiData }}
<BarChart
:height="400"
:chart-data="data"
/>
</template>
the result (shortened) of {{ apiData }} with hundred of items is:
[ { "state": "state 1", "activity": "string", "subactivity": "string", "year": 2015, "surface": "3.5500", "total": 3, "rcs": 3 }, { "state": "state 2", "activity": "string", "subactivity": "string", "year": 2016, "surface": "10.9400", "total": 13, "rcs": 13 }]
if i try to show filterByYear, the first time i have not data and how can i do to call filterByYear when i change the year?
[answer myself] the year was string instead number
how can i update the child component BarChart to update the information?
thank you!

Related

How to capture object props in Vue snapshot tests

I always get [object Object] in place of object props due to object to string coercion when I use snapshot testing. How can I fix it? I've tried wrapping element into JSON.stringify(), but it causes "Converting circular structure to JSON" Error.
The example of a resulting snapshot:
exports[`SalesList.vue Снапшот десктоп 1`] = `
<magic-grid-stub
class="sales-list"
cols="[object Object]"
gaps="[object Object]"
usemin="true"
>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-info-stub
class="item"
content="additionalInfo"
/>
</magic-grid-stub>
`;
I have the simple corresponding snapshot tests, like this one:
import { createLocalVue, shallowMount } from '#vue/test-utils'
import SalesList from '#/components/sales/SalesList.vue'
let localVue
const fakeSale = {
code: 'code',
description: 'description',
title: 'title',
image: 'image',
archive: false,
visible: true,
date_to: '2020/08/01',
short_description: 'short_description',
slug: 'slug',
date_from: '2020/06/01',
seo: {
seo_description: 'seo_description',
seo_title: 'seo_title',
seo_keywords: 'seo_keywords',
},
}
function createWrapper(component, options) {
return shallowMount(component, {
localVue,
...options,
})
}
beforeAll(() => {
localVue = createLocalVue()
})
describe('SalesList.vue', () => {
it('Снапшот десктоп', async () => {
expect.assertions(1)
const wrapper = createWrapper(SalesList, {
propsData: {
sales: Array.from({ length: 4 }, (_, index) => ({
...fakeSale,
slug: `slug-${index}`,
})),
additionalInfo: 'additionalInfo',
},
mocks: {
$device: { isDesktop: true },
},
})
expect(wrapper.element).toMatchSnapshot()
})
})
And the component in question itself:
<script lang="ts">
import SalesItem from '#/components/sales/SalesItem.vue'
import MagicGrid from '#/components/MagicGrid.vue'
import SalesInfo from '#/components/sales/SalesInfo.vue'
import Vue from 'vue'
export default Vue.extend({
name: 'SalesList',
components: {
SalesItem,
MagicGrid,
SalesInfo,
},
props: {
sales: {
type: Array,
required: true,
},
additionalInfo: {
type: String,
default: null,
},
},
computed: {
colsAndGaps(): {
cols: { 0: number }
gaps: { 0: number }
} {
return this.$device.isDesktopOrTablet
? {
cols: {0: 2},
gaps: {0: 30},
}
: {
cols: {0: 1},
gaps: {0: 16},
}
},
},
})
</script>
<template>
<magic-grid v-bind="colsAndGaps" class="sales-list">
<sales-item
v-for="sale in sales"
:key="sale.slug"
:sale="sale"
class="item"
/>
<sales-info v-if="additionalInfo" :content="additionalInfo" class="item"/>
</magic-grid>
</template>
You could use a custom jest snapshot serializer.
For VueJs 2 you could use https://github.com/tjw-lint/jest-serializer-vue-tjw - but it doesn't work for VueJs 3 (https://github.com/tjw-lint/jest-serializer-vue-tjw/pull/64).
Example configuration for VueJs 2:
npm install jest-serializer-vue-tjw
// package.json
{
...
"jest": {
"snapshotSerializers": ["jest-serializer-vue-tjw"]
}
}

Vue.js and django rest framework for implements a cascading dropdown list

I would need help building a request to my backend API.
I currently have a form with a drop down list. The data in this list comes from this.$Http.get('/ quality/api/affaires/')
Below this drop-down list, I have another list. This list, I would like it to be empty until the 1st is not selected, then it is implemented with data according to the selection above.
Backend side (Django) I have 2 models which are "Affaires" and "AffairesOfs". I used Serialize and I can therefore request each of these models via api/affaires and api/affairesofs
In the "AffairesOfs" model I have a foreignekey (idaffaire) on the id of the "Affaires" model.
Finally, I would like my second list to be made up of all the “affairesofs” linked to the “Affaires” selected.
For now, I have my 2 drop-down lists but I can't find a way to link the second to the first.
I tried different methods found on the internet (with the use of v-model, ...) but could not achieve a result.
I can't even get the value selected from the first list to display it in the console, or in a <span>. I think I need a change event on the first list which ask a getMethod with selected value in parameters ?
example of api/affaire :
{
"id": 1,
"nom": "HORS AFFAIRE",
"adresse": "15, rue de la Gibaudière",
"cp": "49183",
"ville": "Saint-Barthélémy d'Anjou",
"dessinateur": 0,
"conducteur": 0,
"chefdeprojet": null,
"cloture": 0
},
{
"id": 2,
"nom": "Suivi Production",
"adresse": null,
"cp": null,
"ville": null,
"dessinateur": null,
"conducteur": null,
"chefdeprojet": null,
"cloture": 0
},
example of api/affairesofs :
{
"id": 2,
"idaffaire": {
"id": 1042,
"nom": "Schlumberger",
"adresse": "",
"cp": "75007",
"ville": "Paris",
"dessinateur": null,
"conducteur": 6,
"chefdeprojet": 16,
"cloture": 1
},
"dateajout": "2015-12-14T15:08:46Z",
"statut": 2,
"type": 0,
"nom": "Chassis St Do R1 à R3",
"isanalise": 1,
"idpersonnel": 1
},
{
"id": 6,
"idaffaire": {
"id": 1045,
"nom": "LAVAL",
"adresse": "",
"cp": "53000",
"ville": "Laval",
"dessinateur": 3,
"conducteur": 9,
"chefdeprojet": 9,
"cloture": 1
},
and below there is my page :
<div id="starting">
<div class="container">
<div class="row">
<form class="form-group">
<label>N° d'affaire</label>
<select class="col" v-model="affaireSelected">
<option value="">Choisir :</option>
<option v-for="affaire in affaires" v-bind:value="affaire.id">${affaire.id} - ${affaire.nom}</option>
</select>
<span> Selectionné : {{ affaireSelected }}</span>
<label>N° d'OF</label>
<select class="col">
<option value="choisir">Choisir :</option>
<option v-for="of in ofs" :value="of.id">${of.id} - ${of.nom}</option>
</select>
<input type="submit" value="Valider" class="btn btn-success" />
</form>
</div>
</div>
<div class="loading" v-if="loading===true">Loading…/div>
</div>
<!-- vue.js files !-->
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.3.5"></script>
<script type="text/javascript">
new Vue({
el: '#starting',
delimiters: ['${','}'],
data: {
ncs: [],
affaires: [],
ofs: [],
affaireSelected: '',
loading: false,
currentNc: {},
},
mounted: function() {
this.getAffaires();
this.getOfs();
},
methods: {
getAffaires: function() {
this.loading = true;
this.$http.get('/qualite/api/affaires/')
.then((response) => {
this.affaires =response.data;
this.loading = false;
})
.catch((err) => {
this.loading = false;
console.log(err);
})
},
getOfs: function() {
this.loading = true;
this.$http.get('/qualite/api/affairesOf/')
.then((response) => {
this.ofs =response.data;
this.loading = false;
})
.catch((err) => {
this.loading = false;
console.log(err);
})
},
}
});
</script>
Finally found a solution. I need to use a computed property juste like this :
computed: {
ofsByAffaire() {
return this.ofs.filter(oF => oF.idaffaire.id === this.affaireSelected.id);
}
},
then, I juste have to use this computed property on the template :
<select class="col">
<option value="choisir">Choisir :</option>
<option v-for="of in ofsByAffaire" :value="of.id">${of.id} - ${of.nom}</option>
</select>

Vue.js Vuex Unit test on user input, can I consider my test OK when coverage is 100%

I am currently testing one of my children components
I already tested successfully all vuex actions, mutations and getters
When I run this ChangeTitleComonent.spec.js , it passes with 100% coverage.. thanks for feedback
Do I need to write some additional tests when it's 100% covered ? or is this test bad written ?
PARENT
ShoppingListComponent.vue
<template>
<div>
<h2>{{ title }}</h2>
<add-item-component :id='id' #add="addItem"></add-item-component>
<items-component :items="items" :id="id"></items-component>
<div class="footer">
<hr />
<change-title-component :title="title" :id="id"></change-title-component>
</div>
</div>
</template>
<script>
import AddItemComponent from './AddItemComponent'
import ItemsComponent from './ItemsComponent'
import ChangeTitleComponent from './ChangeTitleComponent'
export default {
components: {
AddItemComponent,
ItemsComponent,
ChangeTitleComponent
},
props: ['id', 'title', 'items'],
methods: {
addItem (text) {
this.items.push({
text: text,
checked: false
})
}
}
}
</script>
<style scoped>
.footer {
font-size: 0.7em;
margin-top: 20vh;
}
</style>
CHILDREN
ChangeTitleComponent
<template>
<div>
<em>Change the title of your shopping list here</em>
<input :value="title" #input="onInput({ title: $event.target.value, id: id })"/>
</div>
</template>
<style scoped>
</style>
<script>
import { mapActions } from 'vuex'
export default {
props: ['title', 'id'],
methods: mapActions({ // dispatching actions in components
onInput: 'changeTitle'
})
}
</script>
UNIT TEST
ChangeTitleComponent.spec.js
import Vue from 'vue'
import ChangeTitleComponent from '#/components/ChangeTitleComponent'
import store from '#/vuex/store'
describe('ChangeTitleComponent.vue', () => {
describe('changeTitle', () => {
var component
beforeEach(() => {
var vm = new Vue({
template: '<change-title-component :title="title" :id="id" ref="changetitlecomponent">' +
'</change-title-component></div>',
components: {
ChangeTitleComponent
},
props: ['title', 'id'],
store
}).$mount()
component = vm.$refs.changetitlecomponent
})
it('should change the title', () => {
// check component label text
expect(component.$el.textContent).to.equal('Change the title of your shopping list here ')
// simulate input Enter event
const input = component.$el.querySelector('input')
input.value = 'My New Title'
const enterEvent = new window.Event('keypress', { which: 13 })
input.dispatchEvent(enterEvent)
component._watcher.run()
})
})
})

Vue component testing using Karma: 'undefined is not an object'

I am working on an app which was created with the Vue loader's webpack template.
I included testing with Karma as an option when creating the project, so it was all set up and I haven't changed any of the config.
The app is a Github user lookup which currently consists of three components; App.vue, Stats.vue and UserForm.vue. The stats and form components are children of the containing app component.
Here is App.vue:
<template>
<div id="app">
<user-form
v-model="inputValue"
#go="submit"
:input-value="inputValue"
></user-form>
<stats
:username="username"
:avatar="avatar"
:fave-lang="faveLang"
:followers="followers"
></stats>
</div>
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import _ from 'lodash'
import UserForm from './components/UserForm'
import Stats from './components/Stats'
Vue.use(VueAxios, axios)
export default {
name: 'app',
components: {
UserForm,
Stats
},
data () {
return {
inputValue: '',
username: '',
avatar: '',
followers: [],
faveLang: '',
urlBase: 'https://api.github.com/users'
}
},
methods: {
submit () {
if (this.inputValue) {
const api = `${this.urlBase}/${this.inputValue}`
this.fetchUser(api)
}
},
fetchUser (api) {
Vue.axios.get(api).then((response) => {
const { data } = response
this.inputValue = ''
this.username = data.login
this.avatar = data.avatar_url
this.fetchFollowers()
this.fetchFaveLang()
}).catch(error => {
console.warn('ERROR:', error)
})
},
fetchFollowers () {
Vue.axios.get(`${this.urlBase}/${this.username}/followers`).then(followersResponse => {
this.followers = followersResponse.data.map(follower => {
return follower.login
})
})
},
fetchFaveLang () {
Vue.axios.get(`${this.urlBase}/${this.username}/repos`).then(reposResponse => {
const langs = reposResponse.data.map(repo => {
return repo.language
})
// Get most commonly occurring string from array
const faveLang = _.chain(langs).countBy().toPairs().maxBy(_.last).head().value()
if (faveLang !== 'null') {
this.faveLang = faveLang
} else {
this.faveLang = ''
}
})
}
}
}
</script>
<style lang="stylus">
body
background-color goldenrod
</style>
Here is Stats.vue:
<template>
<div class="container">
<h1 class="username" v-if="username">{{username}}</h1>
<img v-if="avatar" :src="avatar" class="avatar">
<h2 v-if="faveLang">Favourite Language: {{faveLang}}</h2>
<h3 v-if="followers.length > 0">Followers ({{followers.length}}):</h3>
<ul v-if="followers.length > 0">
<li v-for="follower in followers">
{{follower}}
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'stats',
props: [
'username',
'avatar',
'faveLang',
'followers'
]
}
</script>
<style lang="stylus" scoped>
h1
font-size 44px
.avatar
height 200px
width 200px
border-radius 10%
.container
display flex
align-items center
flex-flow column
font-family Comic Sans MS
</style>
And here is UserForm.vue:
<template>
<form #submit.prevent="handleSubmit">
<input
class="input"
:value="inputValue"
#input="updateValue($event.target.value)"
type="text"
placeholder="Enter a GitHub username..."
>
<button class="button">Go!</button>
</form>
</template>
<script>
export default {
props: ['inputValue'],
name: 'user-form',
methods: {
updateValue (value) {
this.$emit('input', value)
},
handleSubmit () {
this.$emit('go')
}
}
}
</script>
<style lang="stylus" scoped>
input
width 320px
input,
button
font-size 25px
form
display flex
justify-content center
</style>
I wrote a trivial test for UserForm.vue which test's the outerHTML of the <button>:
import Vue from 'vue'
import UserForm from 'src/components/UserForm'
describe('UserForm.vue', () => {
it('should have a data-attribute in the button outerHTML', () => {
const vm = new Vue({
el: document.createElement('div'),
render: (h) => h(UserForm)
})
expect(vm.$el.querySelector('.button').outerHTML)
.to.include('data-v')
})
})
This works fine; the output when running npm run unit is:
UserForm.vue
✓ should have a data-attribute in the button outerHTML
However, when I tried to write a similarly simple test for Stats.vue based on the documentation, I ran into a problem.
Here is the test:
import Vue from 'vue'
import Stats from 'src/components/Stats'
// Inspect the generated HTML after a state update
it('updates the rendered message when vm.message updates', done => {
const vm = new Vue(Stats).$mount()
vm.username = 'foo'
// wait a "tick" after state change before asserting DOM updates
Vue.nextTick(() => {
expect(vm.$el.querySelector('.username').textContent).toBe('foo')
done()
})
})
and here is the respective error when running npm run unit:
ERROR LOG: '[Vue warn]: Error when rendering root instance: '
✗ updates the rendered message when vm.message updates
undefined is not an object (evaluating '_vm.followers.length')
I have tried the following in an attempt to get the test working:
Change how the vm is created in the Stats test to be the same as the UserForm test - same error is returned
Test individual parts of the component, for example the textContent of a div in the component - same error is returned
Why is the error referring to _vm.followers.length? What is _vm with an underscore in front? How can I get around this issue to be able to successfully test my component?
(Repo with all code: https://github.com/alanbuchanan/vue-github-lookup-2)
Why is the error referring to _vm.followers.length? What is _vm with an underscore in front?
This piece of code is from the render function that Vue compiled your template into. _vm is a placeholder that gets inserted automatically into all Javascript expressions when vue-loader converts the template into a render function during build - it does that to provide access to the component.
When you do this in your template:
{{followers.length}}
The compiled result in the render function for this piece of code will be:
_vm.followers.length
Now, why does the error happen in the first place? Because you have defined a prop followers on your component, but don't provide any data for it - therefore, the prop's value is undefined
Solution: either you provide a default value for the prop:
// Stats.vue
props: {
followers: { default: () => [] }, // function required to return fresh object
// ... other props
}
Or you propvide acual values for the prop:
// in the test:
const vm = new Vue({
...Stats,
propsData: {
followers: [/* ... actual data*/]
}
}).$mount()

twitter typeahead.js autocomplete remote not working

I have a site with stocks. I would like to add typeahead functionality to my bootstrap template. Since there are about 5000 stocks and will be even more in the future. I am using haystack with whoosh index. I should be using remote version of typeahead.js, but it is not working. Could you please take a look and tell me what am I missing?
<script type="text/javascript">
var stocks = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 5,
remote: {
url: "/search/autocomplete/",
replace: function(url, query) {
return url + "?q=" + query;
},
filter: function(stocks) {
return $.map(stocks, function(data) {
return {
tokens: data.tokens,
symbol: data.symbol,
name: data.name
}
});
}
}
});
stocks.initialize();
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: 'name',
minLength: 1, // send AJAX request only after user type in at least X characters
source: stocks.ttAdapter()
});
</script>
This is my form
<form class="input-prepend" method="get" action="/search/">
<div id="remote">
<button type="submit" class="btn">Search</button>
<input type="text" class="typeahead" id="id_q" placeholder="Stock symbol or name" autocomplete="off" name="q">
</div>
</form>
Urls.py
url(r'^search/autocomplete/', 'stocks.views.autocomplete'),
url(r'^search/', include('haystack.urls')),
autocomplete view
from haystack.query import SearchQuerySet
import json
def autocomplete(request):
sqs = SearchQuerySet().autocomplete(content_auto=request.GET.get('q', ''))[:5]
array = []
for result in sqs:
data = {"symbol": str(result.symbol),
"name": str(result.name),
"tokens": str(result.name).split()}
array.insert(0, data)
return HttpResponse(json.dumps(array), content_type='application/json')
json response:
[{"tokens": ["Arbor", "Realty", "Trus"], "symbol": "ABR", "name": "Arbor Realty Trus"}, {"tokens": ["ABM", "Industries", "In"], "symbol": "ABM", "name": "ABM Industries In"}, {"tokens": ["AmerisourceBergen"], "symbol": "ABC", "name": "AmerisourceBergen"}, {"tokens": ["ABB", "Ltd", "Common", "St"], "symbol": "ABB", "name": "ABB Ltd Common St"}, {"tokens": ["Allianceberstein"], "symbol": "AB", "name": "Allianceberstein "}]
This is my domain name: digrin.com and this is autocomplete url.
What am I missing?
I can see two problems:
1) Your script declaration is missing a type attribute:
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.js"></script>
<script type='text/javascript' src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
add "type='text/javascript'" to the script declarations for jquery and bootstrap.
A more modern way of declaring your script tags can be found here.
2) To initialise Typeahead you need to place the code into your jQuery ready method i.e.
$(function(){
var stocks = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 5,
remote: {
url: "/search/autocomplete/",
replace: function(url, query) {
return url + "?q=" + query;
},
filter: function(stocks) {
return $.map(stocks, function(data) {
return {
tokens: data.tokens,
symbol: data.symbol,
name: data.name
}
});
}
}
});
stocks.initialize();
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: 'name',
minLength: 1, // send AJAX request only after user type in at least X characters
source: stocks.ttAdapter()
});
});
As it is currently the typeahead code wont get loaded.