How to test methods imported from other components or JS file - vuejs2

I don´t have much experience with unit testing.
What is the proper way to test a method imported from a JS file or from another component?
This is a sample component I created a localSum just to use on the test.
<template>
<div class="fixed-center text-center text-h2">
<p>{{ getSum }}</p>
</div>
</template>
<script>
import { sum } from './testComponent.js';
export default {
name: 'TestComponent',
data() {
return {
a: 10,
b: 20
}
},
computed: {
getSum() {
return sum(this.a, this.b);
}
},
methods: {
localSum(a, b) {
return a + b;
}
}
};
</script>
The JS file:
export function sum(a, b) {
return a + b;
}
This is the test, maybe I should not be using wrapper.vm to access the method?
One note: On the real component I don't want to test the method directly, which is why I did not import sum from the JS file.
import { mount } from '#vue/test-utils';
import TestComponent from '#components/TestComponent.vue';
describe('Testing component', () => {
test('Testing local method', () => {
const wrapper = mount(TestComponent);
expect(wrapper.vm.localSum(10, 20)).toBe(30);
});
test('Testing method from js file', () => {
const wrapper = mount(TestComponent);
expect(wrapper.vm.getSum(10, 20)).toBe(30);
});
});
Test result:
Testing component
✓ Testing local method (6 ms)
✕ Testing method from js file (2 ms)
● Testing component › Testing method from js file
TypeError: wrapper.vm.getSum is not a function
Thanks!

In your example getSum() is a computed property that doesn't take any argument.
Therefore to test it you probably just need to do:
expect(wrapper.vm.getSum).toBe(30);
instead of:
expect(wrapper.vm.getSum(10, 20)).toBe(30);

Related

Vue js 3 render dynamic component template from server

I have a problem with Vue 3, using vue from CDN.
I want to use a template generated by the server, the template is changed but methods and data are not bound.
<script>
// reproduction of the issue in vue3 vite
import { compile, computed, h } from 'vue/dist/vue.esm-bundler'; // vite
// import { compile, computed, h } from 'vue/dist/vue.esm-bundler'; // webpack
export default {
data() {
return {
htmlTemplate: '<span #click="test()">this is a test {{ testVariable }}</span>', // This is a test from what would be loaded from the server
testVariable: 'test variable',
}
},
methods: {
test() {
console.log('test');
}
},
render() {
const textCompRef = computed(() => ({ render: compile(this.htmlTemplate) }));
console.log('textCompRef', textCompRef);
return h(textCompRef.value);
}
}
</script>
When I click on this is a test then vue#3:1807 Uncaught TypeError: test is not a function
Can someone point me in the right direction?
Thanks in advance
I tried setting the template in the create life cycle with this.$options.template = response from the server that worked on 3-rd click and was not changing when new template is loaded.

Making request to Spring Boot Admin server from custom view?

I'm trying to add a custom view with some administrative utilities to Spring Boot Admin. The idea is to implement these as endpoints in Springboot Admin and call these endpoints from my custom view, but I don't know how to make a call to the server itself.
When a custom view has parent: 'instances' it will get an axios client for connecting to the current instance, but since the view I'm building isn't tied to a specific instance it doesn't have this. I'm aware I can install axios as a dependency, but I'd like to avoid that if possible to reduce build times. Since SBA itself depends on axios it seems I shouldn't have to install it myself.
Based on this sample, this is what I have right now:
index.js
/* global SBA */
import example from './example';
import exampleEndpoint from './example-endpoint';
SBA.use({
install({viewRegistry}) {
viewRegistry.addView({
name: 'example',
path: '/example',
component: example,
label: 'Example',
order: 1000,
});
}
});
example.vue
<template>
<div>
<h1>Example View</h1>
<p>
<b>GET /example:</b> <span v-text="exampleResponse" />
</p>
</div>
</template>
<script>
export default {
props: {
applications: {
type: Array,
required: true
}
},
data: () => ({ exampleResponse: "No response" }),
async created() {
const response = await this.axios.get("example");
this.exampleResponse = response.response;
},
};
</script>
ExampleController.kt
#RestController
#RequestMapping("/example")
class ExampleController {
#GetMapping
fun helloWorld() = mapOf("response" to "Hello world!")
}
Console says that it can't read property get of undefined (i.e. this.axios is undefined). Text reads "GET /example: No response"
I'm not sure if this is the best way to do it, but it is a way.
I noticed that I do have access to the desired axios instance within the SBA.use { install(...) { } } block, and learned that this can be passed as a property down to the view.
index.js
/* global SBA */
import example from './example';
import exampleEndpoint from './example-endpoint';
SBA.use({
install({viewRegistry, axios}) {
viewRegistry.addView({
name: 'example',
path: '/example',
component: example,
label: 'Example',
order: 1000,
// this is where we pass it down with the props
// first part is the name, second is the value
props: { "axios": axios },
});
}
});
example.vue
<template>
<div>
<h1>Example View</h1>
<p>
<b>GET /example:</b> <span v-text="exampleResponse" />
</p>
</div>
</template>
<script>
export default {
props: {
applications: { type: Array, required: true },
// this is where we retrieve the prop. the name of the field should
// correspond to the name given above
axios: { type: Object, required: true },
},
data: () => ({
exampleResponse: "No response",
}),
async created() {
// Now we can use our axios instance! And it will be correctly
// configured for talking to Springboot Admin
this.axios.get("example")
.then(r => { this.exampleResponse = r.data.response; })
.catch(() => { this.exampleResponse = "Request failed!" });
},
};
</script>
Based on the code given, it looks like you don't have axios initialized to how you want to use it.
You're calling it via this.axios but it's not in your component i.e
data() {
return {
axios: require("axios") // usually this is imported at the top
}
}
or exposed globally i.e
Vue.prototype.axios = require("axios")
You can simply just import axios and reference it.
<script>
import axios from 'axios';
export default {
created() {
axios.get()
}
}
</script>

Nuxtjs with i18n-iso-countries

I am trying to use i18n-iso-countries to get a list of countries
What I usually do
/plugins/i18nCountries.js
import countries from 'i18n-iso-countries'
console.log(countries.getNames('en'))
function getNames (locale) {
return countries.getNames(locale)
}
export default ({ app }, inject) => {
inject('getNames', (locale) => { return getNames(locale) })
}
The console.log(countries.getNames('en')) statement prints to the console a list of country names
However, when I am inside a vue page/component
//somecomponent.vue
<template>
...
</template>
<script>
export default {
created () {
console.log(this.$getNames('en'))
},
}
</script>
it prints out {}
What can I do to make this library accessible on the client?
You need to register the languages you want to use. If you put the following below the import line, it should work:
countries.registerLocale(require("i18n-iso-countries/langs/en.json"));

Vuejs load directive dynamicly via data property

From the axios i am getting <test-component></test-component> and i want to add this as a component to the example-component
The output is now
<test-component></test-component>
In stead off
test component
Is that possible and how can i achieve that?
App.js:
import Example from './components/ExampleComponent.vue'
import Test from './components/Test.vue'
Vue.component('example-component', Example)
Vue.component('test-component', Test)
const app = new Vue({
el: '#app'
});
ExampleComponent:
<template>
<div class="container">
{{test}}
</div>
</template>
export default {
data() {
return {
test: ''
}
},
created() {
axios.get('/xxxx')
.then(function (response) {
this.test = response.data.testdirective
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
}
TestComponent:
<template>
<div class="container">
test component
</div>
</template>
It is not possible with the runtime-only build of vuejs. You will need to configure your setup to use the full build of vuejs. The docs specify the setup with some build tools like webpack.
Once the vue template compiler is integrated in the runtime. You can use your current approach to render the component dynamicaly.
There is also another approach to this, which is a bit simpler.
You can use dynamic components like this:
<template>
<div>
<component v-if="name" :is="name"></component>
</div>
</template>
<script>
import TestComponent from "./TestComponent.vue"
import Test2Component from "./Test2Component.vue"
import Test3Component from "./Test3Component.vue"
export default {
component: {
TestComponent,
Test2Component,
Test3Component
},
data() {
return {
name: undefined
}
},
created() {
axios.get('/xxxx')
.then(function (response) {
// where 'response.data.testdirective' is the components name
// without <> e.g. "test-component", "test1-component" or "test2-component"
this.name= response.data.testdirective
})
.catch(function (error) {
// handle error
console.log(error);
this.name = undefined
})
.finally(function () {
// always executed
});
}
}
</script>
As you can see, instead of compiling the components on the fly, I import them to get pre-compiled and bind them dynamically via name. No additional setup required!

Nuxt JS load components depending on API response

I'm building a nuxt app to consume the wp rest API. In my fetch method I fetch information about needed components. I can't figure out how to then import all the components and render them. I've tried several methods, but I can't see to make it work.
Here's what works:
<component :is="test" :config="componentList[0]"></component><br>
export default {
async fetch({ store, $axios }) {
await store.dispatch("getPageBySlug", "home");
},
computed: {
test() {
return () => import('~/components/HeroIntro');
}
}
};
Ok so this is easy, nothing special - I could now import the component based on the slug etc. But I need to render multitple components and therefor im doing this:
<component
v-for="component in componentList"
:key="component.acf_fc_layout"
:is="component.acf_fc_layout"
:config="component">
</component>
along with this
export default {
async fetch({ store, $axios }) {
await store.dispatch("getPageBySlug", "home");
},
computed: {
page() {
return this.$store.getters.getPageBySlug("home");
},
componentList() {
return this.page.acf.flexible_content;
},
componentsToImport() {
for(const component of this.componentList) {
() => import('~/components' + component.acf_fc_layout);
}
}
}
};
All I'm getting is
Unknown custom element: HeroIntro - did you register the
component correctly? For recursive components, make sure to provide
the "name" option
How do I archieve what im trying?
edit:
So, after a lot of trying, I could only make it work with using an extra component, "DynamicComponent":
<template>
<component :is="componentFile" :config="config"></component>
</template>
<script>
export default{
name: 'DynamicComponent',
props: {
componentName: String,
config: Object
},
computed: {
componentFile() {
return () => import(`~/components/${this.componentName}.vue`);
}
}
}
</script>
Now in Index.vue
<template>
<main class="container-fluid">
<DynamicComponent
v-for="(component, index) in componentList"
:key="index"
:componentName="component.name"
:config="component"
/>
</main>
</template>
<script>
export default {
components: {
DynamicComponent: () => import("~/components/base/DynamicComponent")
}
I am not sure yet if this is optimal - but for now it works great - any input / opinions would be great!