Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock lifecycle hooks with vue-test-utils

Method one:

const mixin = {
  beforeCreate() {
    // do something
  }
}

mount(TestComponent, {
  mixins: [mixin]
})

and method two:

const mixin = {
  beforeCreate() {
    // do something
  }
}

localVue = createLocalVue()
localVue.mixin(mixin)

mount(TestComponent, {
  localVue
})

both methods not work for me. I get an error: 'Cannot read property 'props' of undefined' on development environment and on CodeSandbox. https://codesandbox.io/s/4031x2r769

How to correctly mock lifecycle hooks?

like image 741
DenniLa2 Avatar asked Aug 11 '18 07:08

DenniLa2


1 Answers

Your examples in question are correct but your CodeSandbox mixin syntax is incorrect(it should be an object). But main problem is that mixin lifecycle hooks are called before component ones, so your msg assignment is overwritten by component(see mixin merging docs).

If you change created in mixin to mounted for example then it will be passed, because HelloWorld does not change msg field in that hook(or hook does not exist).

There is my fixed test code from CodeSandbox:

import { expect } from "chai";
import { mount, createLocalVue } from "@vue/test-utils";
import HelloWord from "../src/components/HelloWorld.vue";

describe("test mocks", () => {
  const localVue = createLocalVue();

  const msg = "from mock";
  let mixin = {
    // change hook to "later" one to  make it work
    mounted() {
      this.msg = msg;
    }
  }

  localVue.mixin(mixin);

  const wrapper = mount(HelloWord, {
    localVue
  });

  it("hook created", () => {
    expect(wrapper.vm.msg).eq(msg);
  });
});
like image 111
Max Sinev Avatar answered Sep 28 '22 05:09

Max Sinev