简体   繁体   中英

how to mock and test this.$parents in vue using vue-test-utils

I am trying to test a vue component that uses this.$parents.props in it.

eg

export default class item extends Vue {
  private point = this.$parent.$props.point;
}

The reason why I think I need to mock this.$parents.$props is because I get an error like this.

TypeError: Cannot read property 'point' of undefined

I have tried mounting options, parentComponent, but it throws an error saying "[vue-test-utils]: options.parentComponent should be a valid Vue component options object".

This is the code I used for testing.

import Parent from "@/components/Parent.vue";

let wrapper: any;
describe("item.vue", () => {
  it("item vue testing", () => {
    wrapper = mount(item, {
        propsData: {
            num: 1,
        },
        parentComponent: Parent
      });

  });
});

What should I do to mock this.$parent.$props? What is the mistake in the above test code?

you can mock like that

    describe("item.vue", () => {
      it("item vue testing", () => {
        wrapper = mount(item, {
            propsData: {
                num: 1,
            },
            parentComponent: Parent
          });
    
        
        //with functions
        wrapper.vm.$parent= jest.fn().mockResolvedValue("return")
        //or property
        wrapper.vm.$parent.$props.point = "value"
      });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM