我尝试根据以下内容引导一个简单的应用程序Vue3,,ViteVitest
我还安装了 vue 3 兼容版本的vue test utils来测试 vue 组件。
\n我在尝试复制文档中的基本示例时遇到错误:
\nimport { mount } from "@vue/test-utils";\nimport { expect, test } from \'vitest\'\n\n\n// The component to test\nconst MessageComponent = {\n template: "<p>{{ msg }}</p>",\n props: ["msg"],\n};\n\ntest("displays message", () => {\n const wrapper = mount(MessageComponent, {\n props: {\n msg: "Hello world",\n },\n });\n\n // Assert the rendered text of the component\n expect(wrapper.text()).toContain("Hello world");\n});\n\nRun Code Online (Sandbox Code Playgroud)\n FAIL src/tests/hello-world.test.ts > displays message\nReferenceError: document is not defined\n …Run Code Online (Sandbox Code Playgroud) 假设我具有以下组件:
import { mapState } from 'vuex';
import externalDependency from '...';
export default {
name: 'Foo',
computed: {
...mapState(['bar'])
},
watch: {
bar () {
externalDependency.doThing(this.bar);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在测试时,我想确保使用externalDependency.doThing()调用bar(来自vuex状态),如下所示:
it('should call externalDependency.doThing with bar', () => {
const wrapper = mount(Foo);
const spy = jest.spyOn(externalDependency, 'doThing');
wrapper.setComputed({bar: 'baz'});
expect(spy).toHaveBeenCalledWith('baz');
});
Run Code Online (Sandbox Code Playgroud)
Vue的test-utils有一个setComputed方法,该方法可以让我目前对其进行测试,但是我不断收到警告,称setComputed将很快被删除,而且我不知道该如何进行测试:
在我的代码中添加环境变量后import.meta.env.VITE_*,使用 vue-test-utils 的测试开始失败,并出现错误:
Jest suite failed to run
error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.
Run Code Online (Sandbox Code Playgroud)
我已经搜索了一些可用的修复程序,但到目前为止没有一个有效。
编辑
jest.config.js 文件:
module.exports = {
preset: "ts-jest",
globals: {},
testEnvironment: "jsdom",
transform: {
"^.+\\.vue$": "@vue/vue3-jest",
"^.+\\js$": "babel-jest"
},
moduleFileExtensions: ["vue", "js", "json", "jsx", "ts", "tsx", "node"],
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/tests/unit/__mocks__/fileMock.js",
"^@/(.*)$": "<rootDir>/src/$1"
}
}
Run Code Online (Sandbox Code Playgroud)
tsconfig.json 文件:
{
"extends": "@vue/tsconfig/tsconfig.web.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue", "tests"],
"compilerOptions": {
"module": "esnext", …Run Code Online (Sandbox Code Playgroud) 我正在尝试对组件方法进行单元测试。这里的问题并未提出如何从单元测试中访问组件方法。
具体来说,给定下面的Vue组件,如何doSomeWork()从单元测试中访问?
Vue组件:
<template>
<div id="ThisStuff">
<span>
Some other stuff is going on here
</span>
</div>
</template>
<script>
import foo from 'bar'
export default {
props: {
ObjectWithStuffInIt: [
{
id: 1
bar: false
},
{
id: 2
bar: false
},
]
},
data: {
foo: "foo"
},
methods: {
doSomeWork: function() {
for (var i = 0; i < ObjectWithStuffInIt.length; i++) {
if (foo === "diddly") {
ObjectWithStuffInIt[i].bar = true;
}
}
}
}
} …Run Code Online (Sandbox Code Playgroud) 目前,我正在为我的项目实施单元测试,并且其中包含一个文件window.location.href。
我想对此进行测试,这是我的示例代码:
it("method A should work correctly", () => {
const url = "http://dummy.com";
Object.defineProperty(window.location, "href", {
value: url,
writable: true
});
const data = {
id: "123",
name: null
};
window.location.href = url;
wrapper.vm.methodA(data);
expect(window.location.href).toEqual(url);
});
Run Code Online (Sandbox Code Playgroud)
但是我得到这个错误:
TypeError: Cannot redefine property: href
at Function.defineProperty (<anonymous>)
Run Code Online (Sandbox Code Playgroud)
我尝试了一些解决方案,但没有解决。我需要一些提示来帮助我摆脱困境。请帮助。
我正在测试 Vue 组件,但在测试按钮的禁用状态时遇到问题。如何在测试中访问按钮的禁用状态?
我尝试过使用,.attributes()但在这种情况下,该方法仅返回未由v-bind. SubmitButton.attributes().disabled总是null。
成分
<button
id="edit-resource-modal-submit"
class="btn btn-sm btn-primary modal-button"
:disabled="loadingResource || !formValid"
@click="submit"
>
Save
</button>
Run Code Online (Sandbox Code Playgroud)
测试
describe('Disables buttons if', () => {
beforeEach(async() => {
await wrapper.setProps({ isModalOpen: true });
});
it('modal is loading', async() => {
wrapper.vm.loadingResource = true;
const SubmitButton = wrapper.find('#edit-resource-modal-submit');
expect(SubmitButton.exists()).toBe(true);
expect(SubmitButton.attributes().disabled).toBe('true');
});
});
Run Code Online (Sandbox Code Playgroud)
.attributes() 仅返回
{
id: 'edit-resource-modal-submit',
class: 'btn btn-sm btn-primary modal-button'
}
Run Code Online (Sandbox Code Playgroud) 在Vue.js文档中,有一个自定义输入组件的示例.我试图找出如何为这样的组件编写单元测试.组件的用法如下所示
<currency-input v-model="price"></currency-input>
Run Code Online (Sandbox Code Playgroud)
完整的实施可以在https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events找到
文件说
因此,对于要使用的组件
v-model,它应该(这些可以在2.2.0+中配置):
- 接受价值道具
- 使用新值发出输入事件
我如何编写一个单元测试来确保我已经编写了这个组件以便它可以使用v-model?理想情况下,我不想专门测试这两个条件,我想测试一下行为,当组件内的值发生变化时,它也会在模型中发生变化.
我正在使用Jest使用vue-test-utils库来运行我的测试.
即使我已经将VueRouter添加到localVue实例,它也说它实际上找不到路由器链接组件.如果代码看起来有点时髦,那是因为我使用TypeScript,但它应该非常接近ES6 ...主要的是@Prop()与传递道具相同:{..}
Vue组件:
<template>
<div>
<div class="temp">
<div>
<router-link :to="temp.url">{{temp.name}}</router-link>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Prop } from 'vue-property-decorator'
import { Temp } from './Temp'
@Component({
name: 'temp'
})
export default class TempComponent extends Vue {
@Prop() private temp: Temp
}
</script>
<style lang="scss" scoped>
.temp {
padding-top: 10px;
}
</style>
Run Code Online (Sandbox Code Playgroud)
临时模型:
export class Temp {
public static Default: Temp = new Temp(-1, '')
public url: string
constructor(public …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的 Vue 页面:
<template>
</template>
<script>
created(){
this.doSomething();
}
methods: {
doSomething() {
.....
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
现在,我们要测试这个创建的钩子并检查 doSomething() 方法是否被调用。
这样试过,jest也是在package.json中导入的
import {
shallowMount,
createLocalVue,
} from '@vue/test-utils';
const localVue = createLocalVue();
import Xyx from '/Xyx.vue';
const init = () => {
wrapper = shallowMount(Xyx, { localVue });
cmp = wrapper.vm;
};
describe('#created', () => {
it('#doSomething', () => {
init();
wrapper.setMethods({
doSomething: jest.fn(),
})
expect(cmp.doSomething).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
我可以做这个创建的钩子的单元测试用例吗?
有谁知道如何@vue/test-utils v2在使用Vuetify 3 Beta版本时在库中进行组件测试?我也用它Vue3 composition API来定义我的组件。我在这里找到的文档https://vuetifyjs.com/en/getting-started/unit-testing/#spec-tests不起作用,因为它适用于Vuetify v2和@vue/test-utils v1
这是我的plugins/vuetify.js
import '@mdi/font/css/materialdesignicons.css';
import 'vuetify/styles';
import { createVuetify } from 'vuetify';
export default createVuetify();
Run Code Online (Sandbox Code Playgroud)
这是我在 NavBar.spec.js 中的代码
import { mount } from '@vue/test-utils';
import NavBar from '../NavBar.vue';
import Vuetify from '../../plugins/vuetify';
describe('NavBar', () => {
it('No properties [correct]', () => {
mount(NavBar, {
props: {},
global: {
plugins: [Vuetify]
}
});
// check if navbar renders
cy.get('.main')
.first();
});
});
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误: …
vue-test-utils ×10
vue.js ×8
jestjs ×5
vuejs2 ×4
unit-testing ×2
vite ×2
vuex ×2
components ×1
jasmine ×1
javascript ×1
vue-router ×1
vuejs3 ×1
vuetify.js ×1