@@ -903,4 +903,96 @@ it('correctly prints diff with asymmetric matchers', () => {
903903 }
904904} )
905905
906+ it ( 'toHaveProperty error diff' , ( ) => {
907+ setupColors ( getDefaultColors ( ) )
908+
909+ // make it easy for dev who trims trailing whitespace on IDE
910+ function trim ( s : string ) : string {
911+ return s . replaceAll ( / * $ / gm, '' )
912+ }
913+
914+ function getError ( f : ( ) => unknown ) {
915+ try {
916+ f ( )
917+ return expect . unreachable ( )
918+ }
919+ catch ( error ) {
920+ const processed = processError ( error )
921+ return [ processed . message , trim ( processed . diff ) ]
922+ }
923+ }
924+
925+ // non match value
926+ expect ( getError ( ( ) => expect ( { name : 'foo' } ) . toHaveProperty ( 'name' , 'bar' ) ) ) . toMatchInlineSnapshot ( `
927+ [
928+ "expected { name: 'foo' } to have property "name" with value 'bar'",
929+ "- Expected
930+ + Received
931+
932+ - bar
933+ + foo",
934+ ]
935+ ` )
936+
937+ // non match key
938+ expect ( getError ( ( ) => expect ( { noName : 'foo' } ) . toHaveProperty ( 'name' , 'bar' ) ) ) . toMatchInlineSnapshot ( `
939+ [
940+ "expected { noName: 'foo' } to have property "name" with value 'bar'",
941+ "- Expected:
942+ "bar"
943+
944+ + Received:
945+ undefined",
946+ ]
947+ ` )
948+
949+ // non match value (with asymmetric matcher)
950+ expect ( getError ( ( ) => expect ( { name : 'foo' } ) . toHaveProperty ( 'name' , expect . any ( Number ) ) ) ) . toMatchInlineSnapshot ( `
951+ [
952+ "expected { name: 'foo' } to have property "name" with value Any{ …(3) }",
953+ "- Expected:
954+ Any<Number>
955+
956+ + Received:
957+ "foo"",
958+ ]
959+ ` )
960+
961+ // non match key (with asymmetric matcher)
962+ expect ( getError ( ( ) => expect ( { noName : 'foo' } ) . toHaveProperty ( 'name' , expect . any ( Number ) ) ) ) . toMatchInlineSnapshot ( `
963+ [
964+ "expected { noName: 'foo' } to have property "name" with value Any{ …(3) }",
965+ "- Expected:
966+ Any<Number>
967+
968+ + Received:
969+ undefined",
970+ ]
971+ ` )
972+
973+ // non match value (deep key)
974+ expect ( getError ( ( ) => expect ( { parent : { name : 'foo' } } ) . toHaveProperty ( 'parent.name' , 'bar' ) ) ) . toMatchInlineSnapshot ( `
975+ [
976+ "expected { parent: { name: 'foo' } } to have property "parent.name" with value 'bar'",
977+ "- Expected
978+ + Received
979+
980+ - bar
981+ + foo",
982+ ]
983+ ` )
984+
985+ // non match key (deep key)
986+ expect ( getError ( ( ) => expect ( { parent : { noName : 'foo' } } ) . toHaveProperty ( 'parent.name' , 'bar' ) ) ) . toMatchInlineSnapshot ( `
987+ [
988+ "expected { parent: { noName: 'foo' } } to have property "parent.name" with value 'bar'",
989+ "- Expected:
990+ "bar"
991+
992+ + Received:
993+ undefined",
994+ ]
995+ ` )
996+ } )
997+
906998it ( 'timeout' , ( ) => new Promise ( resolve => setTimeout ( resolve , 500 ) ) )
0 commit comments