I know how to load asynchronous component in Vue. This
import MyComponent from '#/components/MyComponent'
export default {
components: {
MyComponent
}
}
is replaced like
export default {
components: {
MyComponent: () => import('#/components/MyComponent')
}
}
But how can I replace "named" component import, like this?
import { SweetModal } from 'sweet-modal-vue'
export default {
components: {
SweetModal
}
}
How do I import that asynchronously?
You could use at the same way, but getting your specific component:
export default {
components: {
SweetModal: () => import('sweet-modal-vue').then(m => m.SweetModal)
}
}
I recommend you to read this: Async Vue.js Component
Related
Using vue-test-utils to test the component using pinia, I need to modify the value of the state stored in pinia, but I have tried many methods to no avail. The original component and store files are as follows.
// HelloWorld.vue
<template>
<h1>{{ title }}</h1>
</template>
<script>
import { useTestStore } from "#/stores/test";
import { mapState } from "pinia";
export default {
name: "HelloWorld",
computed: {
...mapState(useTestStore, ["title"]),
},
};
</script>
// #/stores/test.js
import { defineStore } from "pinia";
export const useTestStore = defineStore("test", {
state: () => {
return { title: "hhhhh" };
},
});
The following methods have been tried.
Import the store used within the component to the test code and make changes directly, but the changes cannot affect the component.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
import { useTestStore } from "#/stores/test";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia()],
},
});
const store = useTestStore();
store.title = "xxxxx";
console.log(wrapper.text()) //"hhhhh";
});
Using the initialState in an attempt to overwrite the contents of the original store, but again without any effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia({ initialState: { title: "xxxxx" } })],
},
});
console.log(wrapper.text()) //"hhhhh";
});
Modify the TestingPinia object passed to global.plugins in the test code, but again has no effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const pinia = createTestingPinia();
pinia.state.value.title = "xxxxx";
const wrapper = mount(HelloWorld, {
global: {
plugins: [pinia],
},
});
console.log(wrapper.text()) //"hhhhh";
});
Use global.mocks to mock the states used in the component, but this only works for the states passed in with setup() in the component, while the ones passed in with mapState() have no effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia()],
mocks: { title: "xxxxx" },
},
});
console.log(wrapper.text()) //"hhhhh"
});
This has been resolved using jest.mock().
import { mount } from "#vue/test-utils";
import { createPinia } from "pinia";
import HelloWorld from "#/components/HelloWorld.vue";
jest.mock("#/stores/test", () => {
const { defineStore } = require("pinia");
const useTestStore = defineStore("test", { state: () => ({ title: "xxxxx" }) });
return { useTestStore };
});
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: { plugins: [createPinia()] },
});
expect(wrapper.text()).toBe("xxxxx");
});
Thanks to Red Panda for this topic. I use "testing-library", and "vue-testing-library" instead of "vue-test-utils" and "jest", but the problem is the same - couldn't change pinia initial data of the store.
I finally found a solution for this issue without mocking the function.
When you $patch data, you just need to await for it. Somehow it helps. My code looks like this and it totally works:
Popup.test.js
import { render, screen } from '#testing-library/vue'
import { createTestingPinia } from '#pinia/testing'
import { popup } from '#/store1/popup/index'
import Popup from '../../components/Popup/index.vue'
describe('Popup component', () => {
test('displays popup with group component', async () => {
render(Popup, {
global: { plugins: [createTestingPinia()] }
})
const store = popup()
await store.$patch({ popupData: 'new name' })
screen.debug()
})
})
OR you can set initialState using this scheme:
import { render, screen } from '#testing-library/vue'
import { createTestingPinia } from '#pinia/testing'
import { popup } from '#/store1/popup/index'
import Popup from '../../components/Popup/index.vue'
test('displays popup with no inner component', async () => {
const { getByTestId } = render(Popup, {
global: {
plugins: [
createTestingPinia({
initialState: {
popup: {
popupData: 'new name'
}
}
})
]
}
})
const store = popup()
screen.debug()
})
Where popup in initialState - is the imported pinia store from #/store1/popup. You can specify any of them there the same way.
Popup.vue
<script>
import { defineAsyncComponent, markRaw } from 'vue'
import { mapState, mapActions } from 'pinia'
import { popup } from '#/store1/popup/index'
export default {
data () {
return {}
},
computed: {
...mapState(popup, ['popupData'])
},
....
I'm working on a project using Vue 3 with composition API styling.
Composition API is used for both components and defining my store.
Here is my store
player.js
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
export const usePlayerStore = defineStore('player',()=>{
const isMainBtnGameClicked = ref(false)
return { isMainBtnGameClicked }
})
MyComponent.vue
//import { usePlayerStore } from '...'
const playerStore = usePlayerStore()
playerStore.isMainBtnGameClicked = true
isMainBtnGameClicked from my store is updated properly.
You can also update variables from components by passing them by reference to the pinia store. It's working in my project.
For sake of saving future me many hours of trouble, there is a non-obvious thing in play here - the event loop. Vue reactivity relies on the event loop running to trigger the cascade of state changes.
When you mount/shallowMount/render a component with vue-test-utils, there is no event loop running automatically. You have to trigger it manually for the reactivity to fire, e.g.
await component.vm.$nextTick;
If you don't want to mess around with ticks, you have to mock the store state/getters/etc. (which the docs strongly lean toward, without explaining the necessity). Here OP mocked the whole store.
See also: Vue-test-utils: using $nextTick multiple times in a single test
We can extract the Vue component's Props into docs by writing this code in MDX
import { Props } from "#storybook/addon-docs/blocks";
import MyComponent from "./index.vue";
<Props of={MyComponent} />;
How can I achieve the same thing in regular stories?
import MyComponent from "./index.vue";
import { Props } from "#storybook/addon-docs/blocks";
// I don't know where to put `Props`
export default {
title: "MyComponent",
};
export const MyComponentStory = () => ({
components: { MyComponent },
template: `
<MyComponent />
`,
});
What should I do to achieve the same thing?
I’m trying to understand why my jest/enzyme tests are failing. I have a component that I use the compose function from redux in, structured as following:
class MyComponent extends Component {
//code here
}
export default compose(
connect(mapStateToProps),
)(MyComponent)
In my jest test, I do this:
Import { MyComponent } from ‘app/MyComponent’;
describe(‘<MyComponent />’, () => {
let component;
beforeEach(() => {
props = {
id: ‘23423’
}
component = shallow(<MyComponent {…props} />);
}
it(‘Loads correctly’, () => {
expect(component.state(‘isLoading’)).toEqual(true);
expect(component.find(‘InnerComponent’).length).toBe(1);
}
However, I get errors like "Cannot read property 'state' of undefined". I understand that using shallow rendering doesn't give me the exact structure that I need, but I'm not sure what else to try to get the right structure. I tried shallow-rendering the wrapped component and then finding the unwrapped component within it, like so, component = shallow(<MyComponent {...props} />).find('MyComponent').shallow();, with no luck. Any other suggestions would be appreciated.
`
Usually you want to test the component and not the integration of the component with redux:
class MyComponent extends Component {
//code here
}
export { MyComponent } // export the component
export default compose(
connect(mapStateToProps),
)(MyComponent)
Also on your test you would import the named export import { MyComponent } from '...' instead of importing the default: import MyComponent from '..'
import { MyComponent } from ‘app/MyComponent’;
describe(‘<MyComponent />’, () => {
let component;
beforeEach(() => {
props = {
id: ‘23423’
}
component = shallow(<MyComponent {…props} />);
}
it(‘Loads correctly’, () => {
expect(component.state(‘isLoading’)).toEqual(true);
expect(component.find(‘InnerComponent’).length).toBe(1);
}
}
If you want to test component interactions with your redux store you need to wrap your component with a <Provider />
import { MyComponent } from ‘app/MyComponent’;
import { Provider } from 'react-redux'
describe(‘<MyComponent />’, () => {
let component;
beforeEach(() => {
props = {
id: ‘23423’
}
component = shallow(<Provider><MyComponent {…props} /></Provider>);
}
You should definitely read the testing section of the redux documentation
I've defined an import on a component. I then have another component that extends off of it. How would I go about defining and accessing the Service that the parent component has imported?
Service
export default {
getSomeData() {
return [1,2,3,4]
}
}
Parent Component
import Service from '../service';
export default {
data() {
return {
testData: 'test'
}
}
}
Child Component
import Component from '../component';
export default {
extends: Component,
mounted() {
console.log(Service.getSomeData()); // [1,2,3,4] Doesn't work, Service not defined.
console.log(this.testData); // 'test' Works
}
}
Generally I would just import Service in the child component and use that function. How do I define it in the parent so that I can access it in the child without having to import it again for other children? I would prefer not to make it into a Vue component and extend it.
Thanks
You can assign it to a data property:
import Service from '../service';
export default {
data() {
return {
testData: 'test',
service: Service
}
}
}
import Component from '../component';
export default {
extends: Component,
mounted() {
console.log(this.service.getSomeData()); // [1,2,3,4]
console.log(this.testData); // 'test' Works
}
}
I am unable to use the #connect() syntax in place of export default connect()
I've noticed that when I use the usual syntax
class PhonePage extends Component { ... }
export default connect(state => ({
testedByPhone: state.phonepage.testedByPhone
}),
(dispatch) => ({
actions: bindActionCreators(testUserPhone, dispatch)
})
)(PhonePage)
I get my state properly registered in my store.
And it looks like this: Object {screenProps: undefined, navigation: Object, testedByPhone: Object}
But when I use the #connect decorator to make things cleaner, I don't get anything listed in my state.
#connect(
state => ({
testedByPhone: state.phonepage.testedByPhone
}),
{ testUserPhone }
)
class PhonePage extends Component { ... }
export default PhonePage
Suddenly it's somehow not actually connecting things: Object {screenProps: undefined, navigation: Object}
What am I doing wrong, and what is the correct way to use the magical #connect decorator that I see everyone using?
The rest of the code, just in case it's needed, in the form of #connect;
'use strict'
import React, { Component } from 'react'
import {
AppRegistry,
StyleSheet,
Text,
ScrollView,
View,
StatusBar,
TouchableHighlight,
Button,
TextInput
} from 'react-native'
import { NavigationActions } from 'react-navigation'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { testUserPhone } from './actions'
import PhoneInput from 'react-native-phone-input'
#connect(
state => ({
testedByPhone: state.phonepage.testedByPhone
}),
{ testUserPhone }
)
class PhonePage extends Component {
constructor(){
super()
}
componentDidMount() {
// this.props.testUserPhone
}
render() {
console.log(this.props)
return(
...
)
}
}
export default PhonePage
// export default connect(state => ({
// testedByPhone: state.phonepage.testedByPhone
// }),
// (dispatch) => ({
// actions: bindActionCreators(testUserPhone, dispatch)
// })
// )(PhonePage)
// module.exports = PhonePage
The #connect decorator, or decorators in general, are not native to JavaScript. However, you can add them in via Babel.
You can read more on it here
npm install --save-dev babel-plugin-transform-decorators-legacy
For babel-6, follow #megaboy101's answer
For babel-7 use this
{
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
]
}