正确测试VEE验证验证的表单与Jest提交

发布于 2025-01-22 13:53:39 字数 4552 浏览 0 评论 0原文

我正在尝试提交使用Vee validate的表格,并测试该表格是否与Jest一起调用基础商店。

这是我的代码:

表单:

<template>
  <div class="flex flex-col justify-center h-screen bg-site-100">
    <!-- Login body -->
    <div class="container">
      <div class="mx-auto w-4/12 p-7 bg-white">

        <!-- Form -->
        <Form id="loginForm" @submit="login" :validation-schema="schema" v-slot="{ errors }">
          <div class="mt-4">
            <div>
              <text-box
                :type="'email'"
                :id="'email'"
                :label="'Your Email'"
                v-model="email"
                :place-holder="'Email'"
                :required="true"
                :error="errors.email"
              />
            </div>

            <div>
              <text-box
                :type="'password'"
                :id="'password'"
                :label="'Parool'"
                v-model="password"
                :place-holder="'Password'"
                :required="true"
                :error="errors.password"
              />
            </div>

            <!-- Submit -->
            <Button
              type="submit"
              id="loginButton"
              :disabled="Object.keys(errors).length > 0"
              class="text-white bg-site-600 w-full hover:bg-site-700 focus:ring-4 focus:ring-site-300 font-medium rounded-md text-sm px-5 py-2.5 mr-2 mb-2 focus:outline-none"
            >
              Log In
            </Button>
          </div>
        </Form>

        
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import * as Yup from "yup";
import { Form } from "vee-validate";
import { defineComponent } from "vue";
import Button from "../core/Button.vue";
import TextBox from "../core/TextBox.vue";
import { mapActions, mapStores } from "pinia";
import { useAuthStore } from "../../store/auth";
import LoginDataType from "../../types/login_data";

export default defineComponent({
  name: "Login",
  components: { TextBox, Form, Button },
  computed: { ...mapStores(useAuthStore) },
  data() {
    return {
      email: "",
      password: "",
      schema: Yup.object().shape({
        email: Yup.string().required("Email is required").email("Email is invalid"),
        password: Yup.string().required("Password is required"),
      }),
    };
  },
  methods: {
    async login() {
      console.log("Logged in mock");
      let data: LoginDataType = {
        email: this.email,
        password: this.password,
      };
      await this.authStore.login(data);
    },
  },
});
</script>

商店:

import { defineStore } from "pinia";

export const useAuthStore = defineStore("auth", {
    state: () => ({
    }),
    getters: {
    },
    actions: {
        async login(data: LoginDataType) {
        // do something
        },
    }
})

测试:

it('logs in correctly when right username and password sent to API', async () => {


            const store = useAuthStore();
            jest.spyOn(store, 'login');

            const wrapper = mount(Login, {
                stubs: ['router-link']
            });

            const email = wrapper.find('input[id="email"]');
            await email.setValue('[email protected]');

            // Check if model is set
            expect(wrapper.vm.email).toBe(testEmail);

            const password = wrapper.find('input[id="password"');
            await password.setValue('testPw');


            // Check if model is set
            expect(wrapper.vm.password).toBe(testPw);

            // Check form exists
            const loginForm = wrapper.find('#loginForm');
            expect(loginForm.exists()).toBe(true);

            await loginForm.trigger('submit');

            // Check if store method has been called
            expect(store.login).toHaveBeenCalled();
            expect(store.login).toHaveBeenCalledWith({
                email: '[email protected]',
                password: 'testPw'
            })

        });

测试失败在期望(store.login)。暗示该表格不会提交。当我用常规的HTML表单标签替换Vee validate组件时,该测试正常工作。

什么可能导致这种行为,对任何帮助得到高度赞赏? :)

I am trying to submit a form that uses vee-validate and test if the form calls the underlying store with Jest.

Here is my code:

Form:

<template>
  <div class="flex flex-col justify-center h-screen bg-site-100">
    <!-- Login body -->
    <div class="container">
      <div class="mx-auto w-4/12 p-7 bg-white">

        <!-- Form -->
        <Form id="loginForm" @submit="login" :validation-schema="schema" v-slot="{ errors }">
          <div class="mt-4">
            <div>
              <text-box
                :type="'email'"
                :id="'email'"
                :label="'Your Email'"
                v-model="email"
                :place-holder="'Email'"
                :required="true"
                :error="errors.email"
              />
            </div>

            <div>
              <text-box
                :type="'password'"
                :id="'password'"
                :label="'Parool'"
                v-model="password"
                :place-holder="'Password'"
                :required="true"
                :error="errors.password"
              />
            </div>

            <!-- Submit -->
            <Button
              type="submit"
              id="loginButton"
              :disabled="Object.keys(errors).length > 0"
              class="text-white bg-site-600 w-full hover:bg-site-700 focus:ring-4 focus:ring-site-300 font-medium rounded-md text-sm px-5 py-2.5 mr-2 mb-2 focus:outline-none"
            >
              Log In
            </Button>
          </div>
        </Form>

        
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import * as Yup from "yup";
import { Form } from "vee-validate";
import { defineComponent } from "vue";
import Button from "../core/Button.vue";
import TextBox from "../core/TextBox.vue";
import { mapActions, mapStores } from "pinia";
import { useAuthStore } from "../../store/auth";
import LoginDataType from "../../types/login_data";

export default defineComponent({
  name: "Login",
  components: { TextBox, Form, Button },
  computed: { ...mapStores(useAuthStore) },
  data() {
    return {
      email: "",
      password: "",
      schema: Yup.object().shape({
        email: Yup.string().required("Email is required").email("Email is invalid"),
        password: Yup.string().required("Password is required"),
      }),
    };
  },
  methods: {
    async login() {
      console.log("Logged in mock");
      let data: LoginDataType = {
        email: this.email,
        password: this.password,
      };
      await this.authStore.login(data);
    },
  },
});
</script>

Store:

import { defineStore } from "pinia";

export const useAuthStore = defineStore("auth", {
    state: () => ({
    }),
    getters: {
    },
    actions: {
        async login(data: LoginDataType) {
        // do something
        },
    }
})

Test:

it('logs in correctly when right username and password sent to API', async () => {


            const store = useAuthStore();
            jest.spyOn(store, 'login');

            const wrapper = mount(Login, {
                stubs: ['router-link']
            });

            const email = wrapper.find('input[id="email"]');
            await email.setValue('[email protected]');

            // Check if model is set
            expect(wrapper.vm.email).toBe(testEmail);

            const password = wrapper.find('input[id="password"');
            await password.setValue('testPw');


            // Check if model is set
            expect(wrapper.vm.password).toBe(testPw);

            // Check form exists
            const loginForm = wrapper.find('#loginForm');
            expect(loginForm.exists()).toBe(true);

            await loginForm.trigger('submit');

            // Check if store method has been called
            expect(store.login).toHaveBeenCalled();
            expect(store.login).toHaveBeenCalledWith({
                email: '[email protected]',
                password: 'testPw'
            })

        });

The test fails at expect(store.login).toHaveBeenCalled(). Implying the form doesn't get submitted. The test works just fine when I replace the vee-validate component Form with a regular HTML form tag.

What might be causing this behaviour any help is highly appreciated? :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

定格我的天空 2025-01-29 13:53:39

聚会有点晚,但我面临同样的问题。我通过使用以下代码修复了它:

await flushPromises();
await waitForExpect(() => {
  // do my expect here
});

这是库中的库中预先关注的内容。 ://vee-validate.logaretm.com/v4/guide/testing/

A little late for the party but I faced the same issue. I fixed it by using the following code:

await flushPromises();
await waitForExpect(() => {
  // do my expect here
});

This is what is preconised by the library in https://vee-validate.logaretm.com/v4/guide/testing/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文