Use Matchers in JSON and YAML snapshots
mainMatchers are functions used as the third argument in MatchJSON or MatchYAML to act as property matchers. They allow you to replace specific paths with placeholders or custom validation logic.
Path Syntax:
- JSON: Uses
gjsonsyntax. - YAML: Uses
github.com/goccy/go-yamlpath syntax.
Built-in Matchers:
match.Any(paths...): Replaces targeted paths with a placeholder (default<Any Value>)..Placeholder(value): Sets a custom placeholder..ErrOnMissingPath(bool): If true (default), errors if the path is missing.
match.Type[T](paths...): Replaces targeted paths with<Type:T>..ErrOnMissingPath(bool): If true (default), errors if the path is missing.
match.Custom(path, func): Allows custom validation. The callback receives the value and should return(any, error). If it returns an error, the test fails..Placeholder(value): Sets a custom placeholder..ErrOnMissingPath(bool): If true (default), errors if the path is missing.
// Example match.Any
match.Any("user.name", "user.email")
// Example match.Type
match.Type[string]("user.info")
// Example match.Custom
match.Custom("user.age", func(val any) (any, error) {
age, ok := val.(float64)
if !ok {
return nil, fmt.Errorf("expected number but got %T", val)
}
return "some number", nil
})