如何使用笑话在Vue.js组件中测试方法的错误

问题描述 投票:0回答:1

如何测试Vue组件的方法createUser()?我想测试例如createUser()firstname < 2方法是否抛出Error。这怎么可能?

我对测试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
1个回答
0
投票

因为在代码中,它引发了错误,所以我们将需要在我们的测试用例中添加一个catch块来测试这种情况。您的案例的PFB示例:

try {
    wrapper.vm.createUser();
  } catch (error) {
    expect(error).toBe('Firstname to short/long/empty');
  }

让我知道您是否遇到任何问题。

© www.soinside.com 2019 - 2024. All rights reserved.