Skip to content

Commit d3846a8

Browse files
rssfrncseddyerburgh
authored andcommitted
feat(functional components): add context to all functional components (#126)
* closes #117 * remove brackets * add test case
1 parent eb0bd58 commit d3846a8

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

src/lib/create-instance.js

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,29 @@ import { throwError } from './util'
1111
import cloneDeep from 'lodash/cloneDeep'
1212
import { compileTemplate } from './compile-template'
1313

14-
export default function createConstructor (component: Component, options: Options): Component {
14+
export default function createConstructor (
15+
component: Component,
16+
options: Options
17+
): Component {
1518
const vue = options.localVue || Vue
1619

17-
if (options.context) {
18-
if (!component.functional) {
19-
throwError('mount.context can only be used when mounting a functional component')
20-
}
21-
22-
if (typeof options.context !== 'object') {
20+
if (component.functional) {
21+
if (options.context && typeof options.context !== 'object') {
2322
throwError('mount.context must be an object')
2423
}
2524
const clonedComponent = cloneDeep(component)
2625
component = {
2726
render (h) {
28-
return h(clonedComponent, options.context)
27+
return h(
28+
clonedComponent,
29+
options.context || component.FunctionalRenderContext
30+
)
2931
}
3032
}
33+
} else if (options.context) {
34+
throwError(
35+
'mount.context can only be used when mounting a functional component'
36+
)
3137
}
3238

3339
if (options.provide) {

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,20 @@ describe('context', () => {
4949
const fn = () => mount(Component, { context })
5050
expect(fn).to.throw().with.property('message', message)
5151
})
52+
53+
it('mounts functional component with a defined context when no context object passed in options', () => {
54+
const defaultValue = '[vue-test-utils]: testProp default value'
55+
const Component = {
56+
functional: true,
57+
props: {
58+
testProp: {
59+
type: String,
60+
default: defaultValue
61+
}
62+
},
63+
render: (h, { props }) => h('div', props.testProp)
64+
}
65+
const wrapper = mount(Component)
66+
expect(wrapper.element.textContent).to.equal(defaultValue)
67+
})
5268
})

0 commit comments

Comments
 (0)