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?
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With