【发布时间】:2020-04-01 08:58:48
【问题描述】:
如何测试我的 Vue 组件的方法createUser()?我想测试 createUser() 方法是否会抛出 Error 如果 firstname < 2 例如。这怎么可能?
我不太熟悉测试 VUE 组件。这是我的第一次,所以我不知道如何访问 VUE 组件以及如何向组件提交例如用户名
<script>
import {ApiService} from '../ApiService.js';
import {User} from '../User.js';
//const API_URL = 'http://localhost:8080';
const apiService = new ApiService();
export default {
name: "CreateUser",
data() {
return {
input: {
username: "",
firstname: "",
lastname: "",
title: "",
password: "",
groupId: "",
groups: [],
},
}
},
/.../
methods: {
getAllGroups() {
apiService.getAllGroups().then((data) => {
this.input.groups = data;
});
},
createUser() {
if (this.input.firstname == null || this.input.firstname.length < 2 || this.input.firstname > 50) {
throw ("Firstname to short/long/empty");
} else {
let user = new User(this.input.username, this.input.lastname, this.input.title, this.input.firstname, this.input.password, this.input.groupId)
apiService.createUser(user).then(() => {
location.reload()
});
}
},
我尝试了以下方法,但有些不起作用
import { shallowMount } from '@vue/test-utils';
import UserModal from "../src/views/UserModal";
describe('UsarModal', () => {
it('should throw error when first name is too short', () => {
const myItems = [
{
username: "Heinz",
firstname: "H",
lasname: "Müller"}
]
const wrapper = shallowMount(UserModal, {
input: {
myItems
}
})
expect(wrapper.vm.createUser()).toThrow("Firstname to short/long/empty")
})
})
【问题讨论】:
-
代码格式和语法修订。
标签: vue.js testing methods jestjs components