import statsd from "../../../src/config/statsd" ; import diff from "jest-diff" ; const parseStatsdMessage = ( stastsdMessage ) : StatsDMessage => { const [ metric , type , tagsString ] = stastsdMessage . split ( "|" ) ; const [ name , value ] = metric . split ( ":" ) ; const tags = { } ; tagsString . substring ( 1 ) . split ( "," ) . map ( ( tagString ) => { const [ key , value ] = tagString . split ( ":" ) ; tags [ key ] = value ; } ) ; return { name , value : parseInt ( value ) , type , tags } ; } ; interface StatsDMessage { name : string ; value : number ; type : string ; tags : Record < string , string > ; } declare global { namespace jest { interface Matchers < R > { toHaveSentMetrics ( ... expectedMetrics ) : R ; } } } expect . extend ( { toHaveSentMetrics ( ... expectedMetrics ) { statsd . mockBuffer = [ ] ; const actualMetrics = statsd . mockBuffer . map ( ( message ) => parseStatsdMessage ( message ) ) ; const matchingMetrics = [ ] ; expectedMetrics . forEach ( ( expectedMetric ) => actualMetrics . find ( ( actualMetric ) => { const matchingName = actualMetric . name === expectedMetric . name ; const matchingType = actualMetric . type === expectedMetric . type ; let matchingValue ; if ( ! expectedMetric . hasOwnProperty ( "value" ) ) { matchingValue = true ; } else if ( typeof expectedMetric . value === "function" ) { matchingValue = expectedMetric . value ( actualMetric . value ) ; } else { matchingValue = actualMetric . value === expectedMetric . value ; } if ( matchingName && matchingType && matchingValue ) { let matchingTags = true ; if ( expectedMetric . tags ) { Object . entries ( expectedMetric . tags ) . forEach ( ( [ name , expectedValue ] ) => { if ( actualMetric . tags [ name ] !== expectedValue ) { matchingTags = false ; } } ) ; } if ( matchingTags ) { matchingMetrics . push ( actualMetric ) ; } } } ) ) ; const pass = matchingMetrics . length === expectedMetrics . length ; return { message : ( ) => { const diffString = diff ( expectedMetrics , actualMetrics , { expand : true } ) ; return `${ this . utils . matcherHint ( "toHaveSentMetrics" , "function" , "metrics" ) }\n\n${ diffString }` ; } , pass } ; } } ) ;