我需要使用它$nextTick来测试我的程序的某些部分。不知何故,它打破了我的测试并使它们始终成功 - 即使它们应该失败。
最小的测试样本如下所示:
import App from "./App";
import { shallowMount } from "@vue/test-utils";
it("should fail", () => {
const wrapper = shallowMount(App);
wrapper.vm.$nextTick(() => {
expect(1).toBe(3);
done();
});
});
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到沙箱示例
如果打开控制台,您应该会发现以下错误消息:
[Vue warn]: Error in nextTick: "Error: expect(received).toBe(expected)
Error: expect(received).toBe(expected)
Run Code Online (Sandbox Code Playgroud)
为什么测试成功?为什么错误会被忽略?如果有这样的$nextTick注释,我该如何正确使用?
我第一次使用 vue-test-utils 在 Vue 应用程序中实现一堆单元测试。测试确实有效,但是,我想干燥代码。
目前我正在将以下代码添加到每个测试中:
const wrapper = shallowMount(ConceptForm, {
localVue,
router,
propsData: { conceptProp: editingConcept }
});
Run Code Online (Sandbox Code Playgroud)
使测试看起来像这样
it('shows the ctas if the state is equal to editing', () => {
const wrapper = shallowMount(ConceptForm, {
localVue,
router,
propsData: { conceptProp: editingConcept }
});
expect(wrapper.find('#ctas').exists()).toBe(true)
});
Run Code Online (Sandbox Code Playgroud)
我这样做是因为我需要将这个特定的 propsData 传递给包装器。有什么方法可以让我在 beforeEach 中浅层安装组件,然后传递 prop 吗?
谢谢!
有人可以向我解释一下为什么在测试中无法通过包装对象访问传入对象的methods模拟函数,而必须首先创建一个变量作为对模拟函数的引用来访问它吗?shallowMount
我尝试过 mount 和shallowMount、创建/安装的钩子,也尝试过直接调用函数,而不是在创建/安装的钩子内部调用。
// TestComponent.spec.js
import TestComponent from '@/components/TestComponent'
import { shallowMount, createLocalVue } from '@vue/test-utils'
const localVue = createLocalVue()
const setLoadingMock = jest.fn() // mock function that is accessible in the test
function createWrapper () {
const defaultMountingOptions = {
localVue,
methods: {
setLoading: setLoadingMock
}
}
return shallowMount(TestComponent, defaultMountingOptions)
}
describe('TestComponent.vue', () => {
let wrapper
beforeEach(() => {
wrapper = createWrapper()
});
it('will call setLoading', () => {
expect(wrapper.vm.setLoading).toHaveBeenCalled()
// FAILS. Console message: …Run Code Online (Sandbox Code Playgroud) 我正在使用 VueJS 和 Jest 对我的组件进行单元测试。
我还使用 Bootstrap Vue 库进行样式设置。我需要在 Jest 测试中使用此插件,以删除一些有关未知插件的控制台警告。
我已经创建了一个安装文件,如下所示:
import { createLocalVue } from '@vue/test-utils'
import BootstrapVue from 'bootstrap-vue'
const localVue = createLocalVue()
localVue.use(BootstrapVue)
Run Code Online (Sandbox Code Playgroud)
并将 Jest 配置为在每次测试之前使用它。
setupFiles: ['<rootDir>/tests/unit/setup']
Run Code Online (Sandbox Code Playgroud)
但是,要从控制台中删除警告,我需要localVue在安装组件时使用该实例:
const wrapper = shallowMount(MyComponent, {
localVue,
propsData: { value: 'someVal }
})
Run Code Online (Sandbox Code Playgroud)
但是,我无法看到将localVue创建的实例放入setup.js测试规范文件中。
如果我这样做:
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
Vue.use(BootstrapVue)
Run Code Online (Sandbox Code Playgroud)
它工作正常,但这很糟糕,因为我们不应该在 Jest 测试中使用 Global Vue 实例。
有没有办法做我想做的事情,或者我是否必须在每个测试文件中构建 Bootstrap Vue 插件(以及其他插件......)?
我有一个自动存根的子组件,带有带有.down修饰符的 keydown 事件。我想在我的测试中触发这个事件。
在 component.vue 中的某处:
<child-component @keydown.down="myFn()" />
Run Code Online (Sandbox Code Playgroud)
在 component.spec.js 中的某处:
// I expect the keydown.down event to be triggered:
wrapper.find({name: 'child-component'}).vm.$emit('keydown.down')
Run Code Online (Sandbox Code Playgroud)
这是行不通的。我能够触发事件的唯一方法是当我删除修饰符时,或者向事件.down添加修饰符时。.native不幸的是我无法使用.native修改器。
我尝试过的其他事情:
wrapper.find({name: 'child-component'}).trigger('keydown.down')
wrapper.find({name: 'child-component'}).vm.$emit('keydown', {keyCode: 40})
对于我的测试,我期望它以长度值 39(最大长度:40)开始,当我按下某个键(即:“a”)时,长度应该为 40。但是,我尝试或查看的任何内容up 似乎不允许我触发 keypress/keydown/keyup 事件。
我的组件:
<q-input
v-model="name"
class="my-class"
maxlength="40"
\>
Run Code Online (Sandbox Code Playgroud)
我的测试:
it('Input should change', async() => {
let wrapper = mount(Component, { name: 'M'.repeat(39) })
let name = wrapper.find('.my-class')
console.log(name.vm.$options.propsData.value) // prints 39 M's as expected
name.trigger('click') // I try clicking the input. I've also tried triggering 'focus'
await wrapper.vm.$nextTick() // I've also tried with and without this
// I've also tried await name.vm.$nextTick()
name.trigger('keydown', { key: 'a' }) // According to their testing docs, this should press …Run Code Online (Sandbox Code Playgroud) 您好,我想检查更改测试内部 select 的值后会发生什么。我正在使用vue-test-utils. 目前我无法检查选择是否发出了输入事件。如果重要的话,我正在使用 Buefy select 组件。
组件的html部分
<b-select
v-model="workHoursType"
>
<option :value="WORKING_HOURS_PERIOD.daily">{{daily}}</option>
<option :value="WORKING_HOURS_PERIOD.weekly">{{weekly}}</option>
</b-select>
Run Code Online (Sandbox Code Playgroud)
测试由于undefined发出而失败
it("once working hours type is set to daily, the hours per week should have no value", async () => {
const wrapper = createWrapper();
const options = wrapper.find("select").findAll("option");
await options.at(1).setSelected();
await flushPromises();
expect(wrapper.emitted().input).toBeDefined();
});
Run Code Online (Sandbox Code Playgroud)
我还看到了v-model基于组件的不同方法,但它仍然对我不起作用。
it("with v-model", async () => {
const wrapper = createWrapper();
const select = wrapper.find("select");
const option = wrapper.findAll("option").at(0);
option.element.selected = true;
select.trigger("change"); …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试 axios 请求,并且需要使用身份验证令牌才能访问端点,但是我的测试失败,因为我收到“Bearer null”并将其输入到我的 headers.Authorization 中。下面是我的实际代码
我正在测试的文件:
this.$axios.get(url, { headers: { Authorization: `Bearer ${localStorage.getItem("access-token")}` } })
.then((response) => {
this.loading = true;
// Get latest barcode created and default it to our "from" input
this.barcodeFrom = response.data.data[response.data.data.length - 1]['i_end_uid'] + 1;
this.barcodeTo = this.barcodeFrom + 1;
this.barcodeRanges = response.data.data;
// Here we add to the data array to make printed barcodes more obvious for the user
this.barcodeRanges.map(item => item['range'] = `${item['i_start_uid']} - ${item['i_end_uid']}`);
// Make newest barcodes appear at the …Run Code Online (Sandbox Code Playgroud) onMounted()我的组件函数中有一个setup()访问 的钩子$route.params property,但是当我$route在测试中模拟该对象时,$route它undefined位于钩子中onMounted(),因此引发错误。这是代码
组件.vue:
<template>
<div>{{ this.$route.params.id }}</div>
</template>
<script lang="ts">
import {defineComponent, onMounted} from 'vue'
import {useRoute} from "vue-router";
export default defineComponent({
name: 'Component',
setup() {
const route = useRoute()
onMounted(() => {
console.log(route.params.id)
})
return {}
}
})
</script>
Run Code Online (Sandbox Code Playgroud)
组件规格:
import {mount} from "@vue/test-utils";
import Component from "@/views/Bundle/Component.vue";
test('test description', async () => {
const mockRoute = {
params: {
id: 1
}
}
const …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用vitest编写一个测试,以断言使用script setup定义的 vue3 组件中的计算属性。
考虑一个简单的组件:
// simple.vue
<script lang="ts" setup>
import { computed } from 'vue';
const hello = computed((): string => {
return 'Hello';
});
</script>
<template>
{{ hello }}
</template>
Run Code Online (Sandbox Code Playgroud)
我的测试是这样的:
describe('Hello', () => {
it('should compute hello', () => {
const wrapper = mount(Hello);
expect(wrapper.vm.hello).toBe('Hello');
});
});
Run Code Online (Sandbox Code Playgroud)
当使用 运行时,该测试实际上按预期工作vitest,因此功能上似乎运行良好。
但是,VSCode 无法看到对象的计算属性vm:
它能够看到普通属性(例如,用defineProps宏定义的属性)。这只是 VSCode 特定工具的问题,还是我应该通过其他方法来测试 vue3 组件中的计算属性?
如果这是首选方法,是否有办法引入计算属性的类型(类似于引入定义的 props 的类型)?
我已经尝试过Vue 测试手册中描述的技术,但这根本不起作用,我认为它一定是特定于 vue2 的。
vue-test-utils ×10
vue.js ×9
jestjs ×6
javascript ×5
unit-testing ×2
vuejs3 ×2
nuxt.js ×1
testing ×1
typescript ×1
vitest ×1