vue3组件mock
时间: 2023-12-23 18:26:38 浏览: 32
在Vue3中,可以使用`@vue/test-utils`和`jest`来进行组件的mock。具体步骤如下:
1. 安装依赖:
```shell
npm install --save-dev @vue/test-utils jest vue-jest babel-jest
```
2. 在`package.json`中添加以下配置:
```json
"jest": {
"moduleFileExtensions": [
"js",
"jsx",
"json",
"vue"
],
"transform": {
"^.+\\.vue$": "vue-jest",
"^.+\\.jsx?$": "babel-jest"
},
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
}
}
```
3. 创建一个mock组件:
```vue
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
}
}
</script>
```
4. 在测试文件中引入`@vue/test-utils`和mock组件:
```javascript
import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
import MockComponent from './MockComponent.vue'
```
5. 使用`shallowMount`方法来创建一个包含mock组件的测试组件:
```javascript
describe('MyComponent', () => {
it('renders a message', () => {
const wrapper = shallowMount(MyComponent, {
propsData: {
message: 'Hello World'
},
global: {
components: {
MockComponent
}
}
})
expect(wrapper.findComponent(MockComponent).exists()).toBe(true)
expect(wrapper.text()).toContain('Hello World')
})
})
```
在这个例子中,我们创建了一个包含`MockComponent`的测试组件,并将其作为全局组件传递给了`shallowMount`方法。然后我们断言测试组件中包含了`MockComponent`,并且渲染出了正确的消息。