Skip to content

Commit

Permalink
feat(props): configured prop argument to readonly
Browse files Browse the repository at this point in the history
  • Loading branch information
nandi95 committed Sep 28, 2021
1 parent 40b3232 commit a7b5f1c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 19 deletions.
62 changes: 45 additions & 17 deletions packages/runtime-core/__tests__/componentProps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,26 +278,54 @@ describe('component props', () => {
expect(root.innerHTML).toBe('<div id="b">2</div>')
})

test('validator arguments', async () => {
const mockFn = jest.fn((...args: any[]) => true)
const Comp = defineComponent({
props: {
foo: {
type: Number,
validator: (value, props) => mockFn(value, props)
describe('validator', () => {
test('validator should be called with two arguments', async () => {
const mockFn = jest.fn((...args: any[]) => true)
const Comp = defineComponent({
props: {
foo: {
type: Number,
validator: (value, props) => mockFn(value, props)
},
bar: {
type: Number
}
},
bar: {
type: Number
}
},
template: `<div />`
template: `<div />`
})

// Note this one is using the main Vue render so it can compile template
// on the fly
const root = document.createElement('div')
domRender(h(Comp, { foo: 1, bar: 2 }), root)
expect(mockFn).toHaveBeenCalledWith(1, { foo: 1, bar: 2 })
})

// Note this one is using the main Vue render so it can compile template
// on the fly
const root = document.createElement('div')
domRender(h(Comp, { foo: 1, bar: 2 }), root)
expect(mockFn).toHaveBeenCalledWith(1, { foo: 1, bar: 2 })
test('validator should not be able to mutate other props', async () => {
const mockFn = jest.fn((...args: any[]) => true)
const Comp = defineComponent({
props: {
foo: {
type: Number,
validator: (value, props) => !!(props.bar = 1)
},
bar: {
type: Number,
validator: value => mockFn(value)
}
},
template: `<div />`
})

// Note this one is using the main Vue render so it can compile template
// on the fly
const root = document.createElement('div')
domRender(h(Comp, { foo: 1, bar: 2 }), root)
expect(
`Set operation on key "bar" failed: target is readonly.`
).toHaveBeenWarnedLast()
expect(mockFn).toHaveBeenCalledWith(2)
})
})

test('warn props mutation', () => {
Expand Down
5 changes: 3 additions & 2 deletions packages/runtime-core/src/componentProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import {
toRaw,
shallowReactive,
trigger,
TriggerOpTypes
TriggerOpTypes,
shallowReadonly
} from '@vue/reactivity'
import {
EMPTY_OBJ,
Expand Down Expand Up @@ -575,7 +576,7 @@ function validateProps(
key,
resolvedValues[key],
opt,
resolvedValues
shallowReadonly(resolvedValues),
!hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key))
)
}
Expand Down

0 comments on commit a7b5f1c

Please sign in to comment.