我有一个专注于输入的指令。我想测试该指令。唯一的问题是我找不到如何测试输入是否聚焦的问题
这是我简单的模拟组件
<template>
<div v-directive>
<input/>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
这是我的指令:
import Vue from 'vue'
export const focusInput = () => {
return {
inserted(el: any) {
el.getElementsByTagName('input')[0].focus()
}
}
}
export default Vue.directive('focus-input', focusInput())
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
import Vue from 'vue'
import { mount , createLocalVue} from '@vue/test-utils'
import FocusInputMock from './mockComponents/FocusInputMock.vue'
import {focusInput} from '@/directives/focusInput';
const localVue = createLocalVue()
localVue.directive('directive', focusInput())
test('update content after changing state', () => {
const wrapper = mount(FocusInputMock, {
localVue
})
Vue.nextTick(function () {
expect(wrapper.find('input')) // I …Run Code Online (Sandbox Code Playgroud) 发出更改组件数据的一个变量的ajax请求后,我正在尝试测试Vue应用程序的模板。此变量(书籍)用于有条件地渲染画廊
语境:我想创建一个画廊,以显示我在后端存储的书。为此,我获取了有关安装组件的书籍。其结果在变量簿中设置。我要测试的是,在ajax调用之后,该组件将书籍与画廊一起呈现
问题:设置books变量后,<div v-else-if='books.length > 0'>SHOW GALLERY</div>应该呈现div ,但是<div v-else class='loader'>Loading</div>仍然呈现“ else” div()
接下来的两个代码块是组件和测试本身:
BookGallery.vue(正在测试的组件)
<template>
<v-content>
<v-container fluid>
/*** Conditional rendering: After the ajax request books > 0, so this div should be rendered ***/
<div v-if='books.length > 0'>SHOW GALLERY</div>
<div v-else class='loader'>Loading</div>
</v-container>
</v-content>
</template>
<script lang='ts'>
import {Component} from 'vue-property-decorator';
import {MyMixin} from '../mixin';
@Component({components: {BookInformation}})
export default class BookGallery extends MyMixin {
public books: string[] = [];
public …Run Code Online (Sandbox Code Playgroud) 我只是想找出在 store 操作后是否调用了组件方法,但出现此错误:
expect(jest.fn())[.not].toHaveBeenCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound mockConstructor]
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
describe('MyComponent.spec.js', () => {
let methods = {
setLocation: jest.fn()
// more methods...
}
it('calls setLocation on undo/redo', () => {
let wrapper = mount(MyComponent, {
store,
localVue,
methods
})
store.dispatch('doUndo')
expect(wrapper.vm.setLocation).toHaveBeenCalled()
})
})
Run Code Online (Sandbox Code Playgroud)
不确定这是否是一个好习惯,但我使用的是实际商店和本地 Vue 实例。
我正在对组件进行一些单元测试。但是,在某些组件中,我有一些运行在mounted钩子上的东西使我的测试失败。我设法模拟了我不需要的方法。但是,我想知道是否有一种解决方法来模拟mounted钩子本身。
@/components/attendeesList.vue
<template>
<div>
<span> This is a test </span>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
JS
<script>
methods: {
testMethod: function() {
// Whatever is in here I have managed to mock it
}
},
mounted: {
this.testMethod();
}
</script>
Run Code Online (Sandbox Code Playgroud)
测试规范.js
import { mount, shallowMount } from '@vue/test-utils'
import test from '@/components/attendeesList.vue'
describe('mocks a method', () => {
test('is a Vue instance', () => {
const wrapper = shallowMount(attendeesList, {
testMethod:jest.fn(),
})
expect(wrapper.isVueInstance()).toBeTruthy()
})
Run Code Online (Sandbox Code Playgroud) 我有一个 UI 库,可以导入到我们的应用程序中。在 UI 库中有一个自定义指令 ,toggle我们使用它来打开和关闭模态。当我运行单元测试时,我收到此错误:
[Vue warn]: Failed to resolve directive: toggle
(found in <Identity>)
Run Code Online (Sandbox Code Playgroud)
在我的Identity组件中,我使用了 UI 库中的一个组件checkbox,它包含了这个指令:
[Vue warn]: Failed to resolve directive: toggle
(found in <Identity>)
Run Code Online (Sandbox Code Playgroud)
如何在我的Identity.spec.js? 导入后,我有:
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use('toggle')
Run Code Online (Sandbox Code Playgroud) 在此文章中解释了如何在VueJS使用全局事件总线。它描述了使用在单独文件中定义的事件总线的通用方法的替代方法:
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;
Run Code Online (Sandbox Code Playgroud)
这必须在需要它的每个 SFC 中导入。另一种方法是将全局事件总线附加到主 Vue 实例:
// main.js
import Vue from 'vue';
Vue.prototype.$eventBus = new Vue(); // I call it here $eventBus instead of $eventHub
new Vue({
el: '#app',
template: '<App/>',
});
// or alternatively
import Vue from 'vue';
import App from './App.vue';
Vue.prototype.$eventBus = new Vue();
new Vue({
render: (h): h(App),
}).$mount('#app');
Run Code Online (Sandbox Code Playgroud)
现在我有一个问题,我不知道如何在单元测试中使用以这种方式创建的全局事件总线。
已经有一个关于使用第一个提到的方法测试全局事件总线的问题,但没有答案被接受。
我按照使用的答案之一中的建议进行了尝试createLocalVue,但这没有帮助:
it('should listen to the …Run Code Online (Sandbox Code Playgroud) 我在 Vue 中的单元测试不仅<v-col>为每个 vuetify 组件输出以下警告:
[Vue 警告]:未知的自定义元素:<v-col> - 您是否正确注册了组件?对于递归组件,请确保提供“名称”选项。
我创建了一个localVue并添加了Vuetify,但这似乎不起作用。这是我的测试用例:
import { shallowMount, createLocalVue } from '@vue/test-utils'
import expect from 'expect'
import ProjetoShow from '../../views/Projeto/ProjetoShow.vue'
import Vuetify from 'vuetify'
describe('ProjetoShow component', () => {
let wrapper
let localVue
beforeEach(() => {
localVue = createLocalVue()
localVue.use(Vuetify)
})
it('renders correctly', ()=> {
let vuetify = new Vuetify()
wrapper = shallowMount(ProjetoShow, {localVue, vuetify})
expect(wrapper.find('h2').text()).toContain('PROJETO')
})
})
Run Code Online (Sandbox Code Playgroud)
我的包版本在 package.json
"devDependencies": {
"@vue/test-utils": "^1.0.0-beta.31",
"axios": "^0.19.0",
"cross-env": "^5.1",
"expect": …Run Code Online (Sandbox Code Playgroud) 我越来越熟悉 jest 和 vue,我想看看如何确保在 prop 更改时触发方法。在这种特殊情况下,这很简单,而且看起来很简单。但它不起作用。
组件观察器
@Watch("id")
public async idChanged() {
this.calculateStatus();
}
Run Code Online (Sandbox Code Playgroud)
beforeEach - 这会为每个测试初始化包装器
beforeEach(async () => {
var httpClient = new PemHttpClient(vue);
var v3ReferenceDatumService = new V3ReferenceDatumService(httpClient, "");
var contractService = new V3ContractService(httpClient, "", v3ReferenceDatumService);
wrapper = mount(AmendmentIdDisplay, {
provide: {
v3ContractService: contractService,
},
propsData: {
id: "82.5.1"
}
});
await wrapper.vm.$nextTick();
})
Run Code Online (Sandbox Code Playgroud)
玩笑测试
let calculateFired = jest.spyOn(wrapper.vm, "calculateStatus");
wrapper.setProps({
...wrapper.props(),
id: "1"
})
await wrapper.vm.$nextTick();
expect(calculateFired).toBeCalled();
Run Code Online (Sandbox Code Playgroud)
我希望间谍增加呼叫计数器,但事实并非如此。它保持为零。如果我手动调用 wrapper.vm.calculateStatus(),间谍工作正常。所以 setProps 要么根本没有触发观察者,要么发生了一些奇怪的参考事件,导致在观察者中调用的方法不是我正在监视的方法。我不确定是哪个。
我正在使用 vue、vuex 和 vuetify 构建登录组件。我决定在商店中使用命名空间身份验证模块,这导致了我的问题。
我正在使用 TDD 来解决这个问题。我的 e2e 测试有效。但我编写了这个单元测试(使用mockStore),它应该只验证是否已调度正确的操作:
describe('Login component', () => {
let wrapper
const mockStore = {
dispatch: jest.fn(),
}
beforeEach(() => {
wrapper = mount(Login, {
localVue,
mocks: { $store: mockStore },
computed: {
error: () => 'test error',
},
data: () => ({
valid: true
})
})
})
it('should dispatch login action', async () => {
wrapper.find('[data-test="username"]').setValue('username')
wrapper.find('[data-test="password"]').setValue('password')
await wrapper.vm.$nextTick()
await wrapper.vm.$nextTick()
wrapper.find('[data-test="login"]').trigger('click')
await wrapper.vm.$nextTick()
expect(mockStore.dispatch).toHaveBeenCalledWith(
`auth/${LOGIN}`,
{ username: 'username', password: 'password' }
) …Run Code Online (Sandbox Code Playgroud) 我试图获得价值,offsetwidth但它总是0
模板.spec.js
import { mount } from '@vue/test-utils';
import Template from '~/components/Template.vue';
describe('Template', () => {
const wrapper = mount(Template);
it('get offsetWidth', async () => {
await wrapper.vm.$nextTick()
console.log(wrapper.element.offsetWidth) // 0
});
});
Run Code Online (Sandbox Code Playgroud)
模板.vue
<template>
<div class="template" style="width:100px">
</div>
</template>
Run Code Online (Sandbox Code Playgroud) vue-test-utils ×10
vue.js ×8
jestjs ×5
javascript ×4
vuejs2 ×4
vuetify.js ×2
babel-jest ×1
mocha.js ×1
unit-testing ×1
vue-events ×1
vuex ×1