Moxy is a function that mocks an object with a proxy by shadowing its properties and methods. This can be vastly useful for testing, when there are properties which are not writable or which you don't want to override to avoid side effects.
This is best explained with the example where moxy origins: Vue's $isServer
property. It defaults to false
and is not configurable, therefore it can not be overridden. However, I needed that property to be true
.
I solved this with moxy by replacing a Vue instance's prototype with a proxy of itself that returns true
when asked for $isServer
:
const vm = new Vue()
console.assert(vm.$isServer === false) // 🤨
const originalPrototype = Object.getPrototypeOf(vm)
const mockedPrototype = moxy(originalPrototype, { $isServer: true })
Object.setPrototypeOf(vm, mockedPrototype)
console.assert(vm.$isServer === true) // 🎉