vuejs / vue-test-utils

Component Test Utils for Vue 2
https://vue-test-utils.vuejs.org
MIT License
3.57k stars 668 forks source link

How to set data of ref inside setup in vue3 #1951

Closed mukeshprajapati-kombee closed 2 years ago

mukeshprajapati-kombee commented 2 years ago

I created a component using the setup in vue3, how can I update vue ref using vue-test-util 2?

import { defineComponent, ref } from "vue";
import { mount } from "@vue/test-utils";

const Nav = defineComponent({
  template: `
    <nav>
      <a id="profile" href="/profile">My Profile</a>
      <a v-if="admin" id="admin" href="/admin">Admin</a>
    </nav>
  `,
  setup() {
    const admin = ref(false);

    return {
      admin,
    };
  },
});

const factory = () => {
  return mount(Nav);
};
describe("ConditionalRenderer", () => {
  test("renders a profile link", () => {
    const wrapper = factory();

    // Here we are implicitly asserting that the
    // element #profile exists.
    const profileLink = wrapper.get("#profile");

    expect(profileLink.text()).toEqual("My Profile");
  });
  test("does not render an admin link", () => {
    const wrapper = mount(Nav);

    // Using `wrapper.get` would throw and make the test fail.
    expect(wrapper.find("#admin").exists()).toBe(false);
  });

  test("renders an admin link", async () => {
    const wrapper = mount(Nav, {
      data() {
        return {
          admin: true,
        };
      },
    });
    // Again, by using `get()` we are implicitly asserting that
    // the element exists.
    expect(wrapper.get("#admin").text()).toEqual("Admin");
  });
});
lmiller1990 commented 2 years ago

Right now there is no way to update a ref inside setup. That said, it looks like there is no way for a user to update the value of admin from the component either - seems like you are attempting to test a case that is impossible in any real application.

You could make admin a prop or something, perhaps?

lmiller1990 commented 2 years ago

Currently no way to modify values in setup, so I'll close this. I don't expect this is something that will be implemented - if you need to update value, I'd recommend doing it like a user with trigger, props, etc.