samedi 7 décembre 2019

How to test an Error of a Method in a Vue.js Component using jest

How can I test the methode createUser() of my Vue component? I want to test if the createUser() method throws an Error if the firstname < 2 for example. How is this possible? Im not really familiar with testing vue components, its my first time. so I have no idea how to get access the vue component and how to submit for a example a username to the component

    <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()
                });
            }
        },

I tried the following, but something doesn't not work

`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")
})

}) `

Aucun commentaire:

Enregistrer un commentaire