Skip to content

Commit

Permalink
fix: matcher toHaveProperty actually tests value (#1958)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Sep 4, 2022
1 parent 025f256 commit 51b5d80
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 19 deletions.
19 changes: 11 additions & 8 deletions packages/vitest/src/integrations/chai/jest-expect.ts
Expand Up @@ -313,18 +313,21 @@ export const JestChaiExpect: ChaiPlugin = (chai, utils) => {

const actual = this._obj
const [propertyName, expected] = args
let pass = false
if (Object.prototype.hasOwnProperty.call(actual, propertyName)) { pass = true }
else {
const { value, exists } = utils.getPathInfo(actual, propertyName)
pass = exists && (args.length === 1 || jestEquals(expected, value))
const getValue = () => {
const hasOwn = Object.prototype.hasOwnProperty.call(actual, propertyName)
if (hasOwn)
return { value: actual[propertyName], exists: true }
return utils.getPathInfo(actual, propertyName)
}
const { value, exists } = getValue()
const pass = exists && (args.length === 1 || jestEquals(expected, value))

const valueString = args.length === 1 ? '' : ` with value ${utils.objDisplay(expected)}`

return this.assert(
pass,
'expected #{this} to have property #{exp}',
'expected #{this} to not have property #{exp}',
expected,
`expected #{this} to have property "${propertyName}"${valueString}`,
`expected #{this} to not have property "${propertyName}"${valueString}`,
actual,
)
})
Expand Down
12 changes: 12 additions & 0 deletions test/core/test/jest-expect.test.ts
Expand Up @@ -178,6 +178,8 @@ describe('jest-expect', () => {
const complex = {
'foo': 1,
'foo.bar[0]': 'baz',
'a-b': true,
'a-b-1.0.0': true,
'bar': {
foo: 'foo',
bar: 100,
Expand All @@ -194,6 +196,8 @@ describe('jest-expect', () => {
expect(complex).toMatchObject({ bar: { bar: 100 } })
expect(complex).toMatchObject({ foo: expect.any(Number) })

expect(complex).toHaveProperty('a-b')
expect(complex).toHaveProperty('a-b-1.0.0')
expect(complex).toHaveProperty('foo')
expect(complex).toHaveProperty('foo', 1)
expect(complex).toHaveProperty('bar.foo', 'foo')
Expand All @@ -208,6 +212,14 @@ describe('jest-expect', () => {
expect(complex).toHaveProperty('bar', expect.any(Object))
expect(complex).toHaveProperty('bar.arr', expect.any(Array))
expect(complex).toHaveProperty('bar.arr.0', expect.anything())

expect(() => {
expect(complex).toHaveProperty('some-unknown-property')
}).toThrowError()

expect(() => {
expect(complex).toHaveProperty('a-b', false)
}).toThrowErrorMatchingInlineSnapshot('"expected { foo: 1, \'foo.bar[0]\': \'baz\', …(3) } to have property \\"a-b\\" with value false"')
})

it('assertions', () => {
Expand Down
11 changes: 0 additions & 11 deletions test/core/test/toHaveProperty.test.ts

This file was deleted.

0 comments on commit 51b5d80

Please sign in to comment.