I have component page. I need connect websocket after page ready;
<script lang="ts">
import Vue from 'vue'
import VueNativeSock from 'vue-native-websocket'
export default Vue.extend({
data() {
return {}
},
methods : {
senddata() {
this.$socket.sendObj({awesome: 'data'})
},
},
mounted(){
Vue.use(VueNativeSock, 'ws://cm2:3000', {
reconnection: true, // (Boolean) whether to reconnect automatically (false)
reconnectionAttempts: 5, // (Number) number of reconnection attempts before giving up (Infinity),
reconnectionDelay: 2000, // (Number) how long to initially wait before attempting a new (1000)
})
}
})
</script>
Everything connects fine, but if I try use $socket in method, I get error while building :
ERROR ERROR in pages/index.vue:20:9 15:42:05
TS2339: Property '$socket' does not exist on type 'CombinedVueInstance<Vue, {}, { senddata(): void; }, unknown, Readonly<Record<never, any>>>'.
18 | senddata() {
19 |
> 20 | this.$socket.sendObj({awesome: 'data'})
| ^^^^^^^
21 |
22 | },
23 |
What do I wrong ? The same if I put wss connection in plugin
The problem solved when I back to commonJS.
Related
In a Laravel + Vue3 + Inertia project which setup using Laravel Mix, how we can create front-end tests?
Especially, I have no idea how to handle Inertia's Share Data, usePage() and useForm methods?
The first error I'm facing is:
TypeError: Cannot read properties of undefined (reading 'someSharedData')
2 |
3 | export const handleSometing = (something) =>
> 4 | usePage().props.value.someSharedData
| ^
5 | ...
6 | )
After googling some useless hours and finding nothing to this exact problem, I've found this solution.
The key was in Jest Partial Mocking!
You can mock useForm, usePage, and then Shared Data using Jest Partial Mocking.
After setup the vue-test-util, I have created this test file and it was working like a charm.
In the below example, the i18n is mocked using the config object of the vue-test-utils.
The Inertia's methods are mocked by jest.mock().
import { config, shallowMount } from '#vue/test-utils'
import Dashboard from '#/Components/ExampleComponent'
config.global.mocks = {
$t: () => '',
}
jest.mock('#inertiajs/inertia-vue3', () => ({
__esModule: true,
...jest.requireActual('#inertiajs/inertia-vue3'), // Keep the rest of Inertia untouched!
useForm: () => ({
/** Return what you need **/
/** Don't forget to mock post, put, ... methods **/
}),
usePage: () => ({
props: {
value: {
someSharedData: 'something',
},
},
}),
}))
test('Render ExampleComponent without crash', () => {
const wrapper = shallowMount(ExampleComponent, {
props: {
otherPageProps: {}
}
})
expect(wrapper.text()).toContain('Hi! I am ExampleComponent.')
})
How to transfer data if I receive an array via Slim?
regions-list :region=#regions
regions-list - my component vue
:region - array with items
#regions - variable with items from backend
Im new with vuex, i think, i need something like this, but don’t know how to convey array with items
This is how you can organize the work of Vuex
export default new Vuex.Store({
state: {
reactions: [],
},
mutations: {
setReactions(state, segment) {
state.reactions = segment;
},
},
actions: {
async loadReactions({ commit }) {
try {
const reactions = '... response/request';
commit('setReactions', reactions); // Here we use mutation to put new data into state.
} catch (e) {
// ...
}
},
},
});
In your component vue regions-list
<template>
<div>{{ reactions }}</div> <!-- Here you can display and look at the content -->
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
name: 'RegionsList',
computed: {
...mapState(['reactions']), // This is get the state
},
created() {
this.loadReactions(); // Here you perform a function that receives data and puts it in state
},
methods: {
...mapActions(['loadReactions']),
},
};
</script>
<style scoped></style>
I'm trying to build a Chat App that use Laravel Broadcast with laravel-echo and pusher but when I'm listening to the channel it returns laravel_echo__WEBPACK_IMPORTED_MODULE_6__.default.private is not a function
here's my script:
<script>
import ConfirmationModal from "../pages/User/ConfirmationModal";
import Message from '../models/Message';
import Echo from 'laravel-echo'
export default {
name: 'UserLayout',
components : {
ConfirmationModal
},
data: () => ({
isLoading : false,
user : {},
drawer: false,
rawConversations : {},
}),
mounted () {
this.user = JSON.parse(localStorage.user);
this.fetchConversations();
},
created () {
Echo.private("userStatus").listen("StatusEvent", e => {
console.log('Event listen CommentSent');
});
}
}
</script>
here's my directory. BTW, I'm using Quasar Framework for my CSS and directory Laravel and Vue is separate.
I'm trying to follow this tutorial https://github.com/jonashackt/spring-boot-vuejs to build a spring boot with vuejs project, I have created the empty vue project using vue create frontend --no-git and then till this step: "Calling a REST service with Axios is simple. Go into the script area of your component, e.g. Hello.vue and add:"
import axios from 'axios'
data ();{
return {
response: [],
errors: []
}
},
callRestService ();{
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
I don't know where exactly this should be added. I created my Hello.vue file under frontend\src\views folder like this and I added it in the src\router\index.js
<template>
<div class="hello">
<button class=”Search__button” #click="callRestService()">CALL Spring Boot REST backend service</button>
<h3>{{ response }}</h3>
</div>
</template>
<script>
import axios from 'axios'
data ();{
return {
response: [],
errors: []
}
},
callRestService ();{
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
But the npm run build gives me this error:
C:\gitercn1\spring-boot-vuejs-copy\frontend\src\views\Hello.vue: 'return' outside of function (13:4)
11 |
12 | data ();{
> 13 | return {
| ^
14 | response: [],
15 | errors: []
16 | }
First, you must add callRestService() in methods or handler (as you are calling the method on button click).
Second, you should remove the unnecessary ; after data() and callRestService().
Third, you should export and name your component if you're going to reuse it somewhere.
Inside your Home.vue component, it could look like so:
<template>
<div class="hello">
<button class=”Search__button” #click="callRestService()">CALL Spring Boot REST backend service</button>
<h3>{{ response }}</h3>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: "HelloComponent",
data() {
return {
response: [],
errors: []
}
},
methods: {
callRestService() {
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
}
</script>
I have looked at the following tutorials https://hackernoon.com/unit-testing-redux-connected-components-692fa3c4441c https://airbnb.io/enzyme/docs/api/shallow.html and tried to create a shallow rendered test of a component but i have actions being triggered on render which collect data and help render the component. how can i mock this?
tests/jest/containers/homecontent.js
import configureStore from 'redux-mock-store'
import { shallow } from 'enzyme';
import { HomeContent } from '../../../app/containers/home';
const passMetaBack = meta => {
this.setState({
title: 'test',
description: 'test'
});
};
// create any initial state needed
const initialState = {};
// here it is possible to pass in any middleware if needed into //configureStore
const mockStore = configureStore();
describe('Login Component', () => {
let wrapper;
let store;
beforeEach(() => {
// our mock login function to replace the one provided by mapDispatchToProps
const mockLoginfn = jest.fn();
//creates the store with any initial state or middleware needed
store = mockStore(initialState)
wrapper = shallow(<HomeContent isGuest={false} isReady={true} priv={{}} passMetaBack={passMetaBack} fetchContents={mockLoginfn} />)
});
it('+++ render the DUMB component', () => {
expect(wrapper.length).toEqual(1)
});
});
The error i get is
FAIL tests/jest/containers/homecontent.test.js
Login Component
✕ +++ render the DUMB component (25ms)
● Login Component › +++ render the DUMB component
TypeError: Cannot read property 'then' of undefined
38 | if(this.props.isReady && this.props.priv != undefined){
39 | let self = this;
> 40 | this.props.fetchContents()
41 | .then(response => {
42 | let data = response.payload.data;
43 | if (data.header.error) {
at HomeContent.initData (app/containers/home.js:40:7)
at HomeContent.render (app/containers/home.js:71:12)
at ReactShallowRenderer._mountClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:195:37)
at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:143:14)
at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:287:35
at withSetStateAllowed (node_modules/enzyme-adapter-utils/build/Utils.js:103:16)
at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:286:68)
at new ShallowWrapper (node_modules/enzyme/build/ShallowWrapper.js:119:22)
at shallow (node_modules/enzyme/build/shallow.js:19:10)
at Object.<anonymous> (tests/jest/containers/homecontent.test.js:24:19)
● Login Component › +++ render the DUMB component
TypeError: Cannot read property 'length' of undefined
26 |
27 | it('+++ render the DUMB component', () => {
> 28 | expect(wrapper.length).toEqual(1)
29 | });
30 | });
31 |
at Object.<anonymous> (tests/jest/containers/homecontent.test.js:28:24)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.218s
Ran all test suites matching /tests\/jest\/containers\/homecontent.test.js/i.
this.props.fetchContents() comes in from an action on the component
mockLoginfn is used as this.props.fetchContents in the component. fetchContents is a function that returns a promise, whereas mockLoginfn is a jest mock function that doesn't return anything.
So, you need to provide a mock implementation for the mockLoginfn so it behaves like a promise. For example (using the code snippet above):
const mockLoginfn = jest.fn();
mockLoginfn.mockImplementation(() => Promise.resolve({
payload: {
data: {
header: {
error: 'some error'
}
}
}
}));