Skip to content

Commit 2d4b999

Browse files
committed
fix: warn if property could not be overwritten by mocks
1 parent 6ed1472 commit 2d4b999

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

docs/en/guides/common-tips.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ mount(Component, {
109109
})
110110
```
111111

112+
**Note some plugins, like Vue Router, add read-only properties to the global Vue constructor. This makes it impossible to reinstall the plugin on a localVue constructor, or add mocks for these properties**
113+
112114
## Mocking Injections
113115

114116
Another strategy for injected props is simply mocking them. You can do that with the `mocks` option:

src/lib/add-mocks.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
// @flow
22
import $$Vue from 'vue'
3+
import { warn } from './util'
34

45
export default function addMocks (mockedProperties: Object, Vue: Component) {
56
Object.keys(mockedProperties).forEach((key) => {
6-
Vue.prototype[key] = mockedProperties[key]
7+
try {
8+
Vue.prototype[key] = mockedProperties[key]
9+
} catch (e) {
10+
warn('could not overwrite property $store, this usually caused by a plugin that has added the property as a read-only value')
11+
}
712
$$Vue.util.defineReactive(Vue, key, mockedProperties[key])
813
})
914
}

test/unit/specs/mount/options/mocks.spec.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,22 @@ describe('mount.mocks', () => {
8484
const freshWrapper = mount(Component)
8585
expect(typeof freshWrapper.vm.$store).to.equal('undefined')
8686
})
87+
88+
it('logs that a property cannot be overwritten if there are problems writing', () => {
89+
const error = sinon.stub(console, 'error')
90+
const localVue = createLocalVue()
91+
Object.defineProperty(localVue.prototype, '$store', {
92+
value: 42
93+
})
94+
const $store = 64
95+
mount(Component, {
96+
localVue,
97+
mocks: {
98+
$store
99+
}
100+
})
101+
const msg = '[vue-test-utils]: could not overwrite property $store, this usually caused by a plugin that has added the property as a read-only value'
102+
expect(error.calledWith(msg)).to.equal(true)
103+
error.restore()
104+
})
87105
})

0 commit comments

Comments
 (0)