Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/createInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,18 @@ export function createInstance(
for (const [k, v] of Object.entries(
global.mocks as { [key: string]: any }
)) {
;(this as any)[k] = v
// the proxy rejects `$x` when `x` is an internal instance field
// (e.g. `$u` from uView), so we define these directly on the context
if (k[0] === '$' && k.slice(1) in this.$) {
Object.defineProperty((this.$ as any).ctx, k, {
configurable: true,
enumerable: true,
writable: true,
value: v
})
} else {
;(this as any)[k] = v
}
}
}
}
Expand Down
39 changes: 39 additions & 0 deletions tests/mountingOptions/mocks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
state: {
count: 1
},
dispatch: vi.fn()

Check warning on line 46 in tests/mountingOptions/mocks.spec.ts

View workflow job for this annotation

GitHub Actions / build (26)

vitest(require-mock-type-parameters)

tests/mountingOptions/mocks.spec.ts:46:20: Missing type parameters on mock function call
}

const wrapper = mount(Foo, {
Expand Down Expand Up @@ -151,4 +151,43 @@
expect(wrapper.text()).toContain('hello')
expect(wrapper.text()).toContain('mocked')
})

it('mocks a global property named after an internal instance field', () => {
// `$u` (uView) matches the internal `u` field of the component instance
const Foo = defineComponent({
template: '<div>{{ $u.title }} {{ title }}</div>',
data() {
return { title: (this as any).$u.title }
}
})

const wrapper = mount(Foo, {
global: {
mocks: { $u: { title: 'mocked' } }
}
})

expect(wrapper.text()).toBe('mocked mocked')
})

it('overrides a global property named after an internal instance field', () => {
const Foo = defineComponent({
template: '<div>{{ $u.title }}</div>'
})

const wrapper = mount(Foo, {
global: {
plugins: [
{
install(app) {
app.config.globalProperties.$u = { title: 'real' }
}
}
],
mocks: { $u: { title: 'mocked' } }
}
})

expect(wrapper.text()).toBe('mocked')
})
})
12 changes: 12 additions & 0 deletions tests/renderToString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,16 @@ describe('renderToString', () => {

spy.mockRestore()
})

it('applies a global mock named after an internal instance field', async () => {
const Component = defineComponent({
template: '<div>{{ $u.title }}</div>'
})

const contents = await renderToString(Component, {
global: { mocks: { $u: { title: 'mocked' } } }
})

expect(contents).toBe('<div>mocked</div>')
})
})
Loading