### Basic TestMain Setup with Clean
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Clean.md
This example shows the minimal setup for using the Clean function within a TestMain function. It ensures cleanup and reporting happen after all tests have executed.
```go
func TestMain(m *testing.M) {
v := m.Run()
snaps.Clean(m)
os.Exit(v)
}
```
--------------------------------
### Install Go Snaps
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Install the go-snaps package using go get. Import the snaps package into your Go code.
```bash
go get github.com/gkampitakis/go-snaps
```
--------------------------------
### Run go-snaps tests locally
Source: https://github.com/gkampitakis/go-snaps/blob/main/contributing.md
Execute tests within the examples directory to verify go-snaps functionality. Ensure you have go>=1.16 installed.
```go
go test ./examples/... -v -race -count=1
```
--------------------------------
### Configuration Precedence Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/configuration.md
Demonstrates configuration precedence where command-line flags override environment variables. The first example will update snapshots regardless of the UPDATE_SNAPS environment variable.
```go
// Command-line takes precedence
snaps.WithConfig(snaps.Update(true)).MatchSnapshot(t, value)
// Even if UPDATE_SNAPS=false, this will try to update
snaps.WithConfig(snaps.Update(false)).MatchSnapshot(t, value)
// This is read-only unless UPDATE_SNAPS=always
```
--------------------------------
### Map Snapshot Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Demonstrates capturing a map as an inline snapshot. Note the order of keys in the inline snapshot.
```go
func TestInlineMap(t *testing.T) {
data := map[string]int{"foo": 1, "bar": 2}
snaps.MatchInlineSnapshot(t, data, snaps.Inline(`map[string]int{"bar":2, "foo":1}`))
}
```
--------------------------------
### JSON Configuration Usage Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/types.md
Demonstrates how to configure JSON snapshot formatting with custom width, indentation, and key sorting options.
```go
snaps.WithConfig(
snaps.JSON(snaps.JSONConfig{
Width: 120,
Indent: " ",
SortKeys: false,
}),
).MatchJSON(t, data)
```
--------------------------------
### Applying JSON Configuration
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Example of applying custom JSON formatting options to a snapshot match.
```go
snaps.JSON(snaps.JSONConfig{
Width: 150,
Indent: " ",
SortKeys: false,
})
```
--------------------------------
### Basic Go-Snaps Usage Pattern
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/README.md
Demonstrates a typical Go-Snaps setup, including importing packages, performing simple and JSON snapshot matching with matchers, and cleaning up snapshots.
```go
import (
"testing"
"github.com/gkampitakis/go-snaps/snaps"
"github.com/gkampitakis/go-snaps/match"
)
func TestExample(t *testing.T) {
// Simple snapshot
snaps.MatchSnapshot(t, "Hello World")
// JSON with matchers
data := map[string]any{
"id": "generated-id",
"timestamp": "2024-01-15T10:30:00Z",
}
snaps.MatchJSON(
t,
data,
match.Any("id", "timestamp"),
)
}
func TestMain(m *testing.M) {
v := m.Run()
snaps.Clean(m)
os.Exit(v)
}
```
--------------------------------
### Clean Function Usage Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/types.md
Example of using the Clean function with options to sort snapshots.
```go
snaps.Clean(m, snaps.CleanOpts{Sort: true})
```
--------------------------------
### Detailed Snapshot Content Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
This example shows the content of a snapshot file for a map, illustrating how different data types are represented. Special characters like '---' at the start of a line are escaped.
```txt
[TestSimple/should_make_a_map_snapshot - 1]
map[string]any{
"mock-0": "value",
"mock-1": int(2),
"mock-2": func() {...},
"mock-3": float32(10.399999618530273),
}
---
```
--------------------------------
### Usage Examples
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Various examples demonstrating the usage of MatchInlineSnapshot for different data types.
```APIDOC
## Usage Examples
### Basic String Snapshot
```go
func TestInlineString(t *testing.T) {
// First run:
snaps.MatchInlineSnapshot(t, "Hello World", nil)
// After update:
snaps.MatchInlineSnapshot(t, "Hello World", snaps.Inline("Hello World"))
}
```
### Numeric Snapshot
```go
func TestInlineNumber(t *testing.T) {
snaps.MatchInlineSnapshot(t, 123, snaps.Inline("int(123)"))
}
```
### Map Snapshot
```go
func TestInlineMap(t *testing.T) {
data := map[string]int{"foo": 1, "bar": 2}
snaps.MatchInlineSnapshot(t, data, snaps.Inline(`map[string]int{"bar":2, "foo":1}`))
}
```
### Multiple Inline Snapshots
```go
func TestMultipleInline(t *testing.T) {
snaps.MatchInlineSnapshot(t, "first", snaps.Inline("first"))
snaps.MatchInlineSnapshot(t, 42, snaps.Inline("int(42)"))
snaps.MatchInlineSnapshot(t, true, snaps.Inline("true"))
}
```
### With Custom Serializer
```go
func TestCustomSerializer(t *testing.T) {
snaps.WithConfig(snaps.Raw()).
MatchInlineSnapshot(t, "value", snaps.Inline("value"))
}
```
### Struct Snapshot
```go
type User struct {
Name string
Age int
}
func TestInlineStruct(t *testing.T) {
user := User{"Alice", 30}
snaps.MatchInlineSnapshot(t, user, snaps.Inline(`User{Name:"Alice", Age:30}`))
}
```
```
--------------------------------
### Workflow: First Run
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Example of the first run workflow to generate snapshots.
```APIDOC
## Workflow: First Run
### Step 1: Initial Test Code
```go
func TestAPI(t *testing.T) {
result := someFunction()
snaps.MatchInlineSnapshot(t, result, nil) // Pass nil initially
}
```
### Step 2: Run Tests with UPDATE_SNAPS=true
```bash
UPDATE_SNAPS=true go test ./...
```
### Step 3: Auto-Updated Test Code
```go
func TestAPI(t *testing.T) {
result := someFunction()
snaps.MatchInlineSnapshot(t, result, snaps.Inline(`map[string]string{"status":"ok", "id":"123"}`))
}
```
### Step 4: Verify and Commit
The test now has the inline snapshot embedded. Subsequent test runs will verify against this snapshot.
```
--------------------------------
### Basic String Snapshot Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Demonstrates using MatchInlineSnapshot for a string value. Shows both the initial call with nil and the updated call with the inline snapshot.
```go
func TestInlineString(t *testing.T) {
// First run:
snaps.MatchInlineSnapshot(t, "Hello World", nil)
// After update:
snaps.MatchInlineSnapshot(t, "Hello World", snaps.Inline("Hello World"))
}
```
--------------------------------
### Snapshot with Custom Configuration
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchSnapshot.md
Applies custom configurations like directory, filename, and serializer to the snapshot process. This example uses a custom serializer to format the output.
```go
func TestWithConfig(t *testing.T) {
snaps.WithConfig(
snaps.Dir("custom_snaps"),
snaps.Filename("my_snaps"),
snaps.Serializer(func(v any) string {
return fmt.Sprintf("custom: %v", v)
}),
).MatchSnapshot(t, someValue)
}
```
--------------------------------
### Custom Serializer Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Demonstrates how to define and use a custom serializer function within `WithConfig`. The function takes any value and returns its string representation.
```go
snaps.Serializer(func(v any) string {
return fmt.Sprintf("%T: %v", v, v)
})
```
--------------------------------
### TestMain with Clean and Sorting Enabled
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Clean.md
This example shows how to use the Clean function with the Sort option enabled, ensuring snapshots are sorted in natural order. Error handling is included.
```go
func TestMain(m *testing.M) {
v := m.Run()
// Sort snapshots in natural order
dirty, err := snaps.Clean(m, snaps.CleanOpts{Sort: true})
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
os.Exit(v)
}
```
--------------------------------
### YAML Snapshot from Bytes
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchYAML.md
This example demonstrates creating a YAML snapshot using a byte slice. The byte slice should contain valid YAML content.
```go
func TestYAMLBytes(t *testing.T) {
yaml := []byte(`
user: alice
age: 30
email: alice@example.com
`)
snaps.MatchYAML(t, yaml)
}
```
--------------------------------
### TestMain with Clean and Error Handling
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Clean.md
This example demonstrates how to integrate Clean into TestMain while properly handling potential errors. It exits with an error code if Clean encounters an issue.
```go
func TestMain(m *testing.M) {
v := m.Run()
dirty, err := snaps.Clean(m)
if err != nil {
fmt.Println("Error cleaning snapshots:", err)
os.Exit(1)
}
if dirty {
fmt.Println("Some snapshots were obsolete.")
os.Exit(1)
}
os.Exit(v)
}
```
--------------------------------
### Struct Snapshot Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Demonstrates capturing a struct as an inline snapshot. The inline snapshot reflects the struct's field names and values.
```go
type User struct {
Name string
Age int
}
func TestInlineStruct(t *testing.T) {
user := User{"Alice", 30}
snaps.MatchInlineSnapshot(t, user, snaps.Inline(`User{Name:"Alice", Age:30}`))
}
```
--------------------------------
### Multiple Snapshots with Custom Extensions
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneSnapshot.md
This example demonstrates how to create standalone snapshots with custom file extensions, enabling syntax highlighting for different content types like HTML and JSON. Each call to `MatchStandaloneSnapshot` with a configured extension will generate a separate file.
```go
func TestWithExtensions(t *testing.T) {
snaps.WithConfig(snaps.Ext(".html")).
MatchStandaloneSnapshot(t, "
content")
// Creates __snapshots__/TestWithExtensions_1.snap.html
snaps.WithConfig(snaps.Ext(".json")).
MatchStandaloneSnapshot(t, map[string]int{"count": 42})
// Creates __snapshots__/TestWithExtensions_2.snap.json
}
```
--------------------------------
### Multiple Inline Snapshots Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Illustrates using multiple MatchInlineSnapshot calls within a single test function for different data types.
```go
func TestMultipleInline(t *testing.T) {
snaps.MatchInlineSnapshot(t, "first", snaps.Inline("first"))
snaps.MatchInlineSnapshot(t, 42, snaps.Inline("int(42)"))
snaps.MatchInlineSnapshot(t, true, snaps.Inline("true"))
}
```
--------------------------------
### Custom Serializer Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Shows how to use MatchInlineSnapshot with a custom serializer, in this case, using snaps.Raw() for raw string output.
```go
func TestCustomSerializer(t *testing.T) {
snaps.WithConfig(snaps.Raw()).
MatchInlineSnapshot(t, "value", snaps.Inline("value"))
}
```
--------------------------------
### Numeric Snapshot Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Shows how to use MatchInlineSnapshot for a numeric value. The inline snapshot includes the type information.
```go
func TestInlineNumber(t *testing.T) {
snaps.MatchInlineSnapshot(t, 123, snaps.Inline("int(123)"))
}
```
--------------------------------
### TestMain with Clean and Skipped Tests Tracking
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Clean.md
This example shows how Clean handles skipped tests. Snapshots associated with skipped tests are correctly excluded from obsolescence marking.
```go
// When using snaps.Skip() in tests, Clean properly excludes them
func TestMain(m *testing.M) {
v := m.Run()
// Snapshots for skipped tests are not marked as obsolete
dirty, err := snaps.Clean(m)
if err != nil {
os.Exit(1)
}
os.Exit(v)
}
```
--------------------------------
### Skip Now (Immediate) Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Use snaps.SkipNow to immediately skip the current test. This is useful for tests that should only run in specific environments, like CI.
```go
func TestExpensive(t *testing.T) {
if !isCI {
snaps.SkipNow(t)
}
runExpensiveTest(t)
}
```
--------------------------------
### Conditional Skip Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Demonstrates using snaps.Skip for conditional skipping based on testing modes, like skipping integration tests when running in short mode.
```go
func TestIntegration(t *testing.T) {
if testing.Short() {
snaps.Skip(t, "Skipping integration tests in short mode")
}
snaps.MatchJSON(t, externalAPIResponse())
}
```
--------------------------------
### Skip Platform-Specific Tests Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Use snaps.Skip to skip tests that are specific to a particular operating system, like a Windows-specific feature.
```go
func TestWindowsFeature(t *testing.T) {
if runtime.GOOS != "windows" {
snaps.Skip(t, "Windows-specific test")
}
snaps.MatchSnapshot(t, windowsSpecificValue())
}
```
--------------------------------
### Skip with Format (Skipf) Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Utilize snaps.Skipf for conditional skipping with formatted messages, similar to testing.Skipf. This is useful for providing detailed reasons for skipping, like database connection failures.
```go
func TestDatabase(t *testing.T) {
db := setupDB()
if db == nil {
snaps.Skipf(t, "Database connection failed: %v", err)
}
snaps.MatchSnapshot(t, db.Query("SELECT * FROM users"))
}
```
--------------------------------
### Multiple JSON Snapshots in a Single Test
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneJSON.md
This example demonstrates how to create multiple, distinct JSON snapshot files within the same test function. Each call to MatchStandaloneJSON generates a new file with an incremented name.
```go
func TestMultipleJSON(t *testing.T) {
user := map[string]string{"name": "Alice", "email": "alice@example.com"}
snaps.MatchStandaloneJSON(t, user)
// Creates TestMultipleJSON_1.snap.json
metadata := map[string]int{"users": 1, "posts": 5}
snaps.MatchStandaloneJSON(t, metadata)
// Creates TestMultipleJSON_2.snap.json
}
```
--------------------------------
### Snapshot File Structure Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Snapshots in go-snaps follow a specific format, including a test identifier and the snapshot data. The TestID helps distinguish multiple snapshot calls within a single test.
```text
[TestName - Number]
---
```
--------------------------------
### Custom JSON Configuration for Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchJSON.md
Configure snapshot formatting with custom width, indentation, and key sorting using `snaps.JSON` and `snaps.WithConfig`. This example sets a custom width, uses two spaces for indentation, and disables key sorting.
```go
func TestCustomJSONConfig(t *testing.T) {
data := map[string]string{
"key1": "value1",
"key2": "value2",
}
snaps.WithConfig(
snaps.JSON(snaps.JSONConfig{
Width: 120,
Indent: " ", // 2 spaces
SortKeys: false, // Keep original order
}),
).MatchJSON(t, data)
}
```
--------------------------------
### Basic Skip Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Use snaps.Skip to skip a test if a condition is met, such as an environment variable not being set. This ensures the test's snapshot is not marked obsolete.
```go
func TestFeature(t *testing.T) {
if os.Getenv("ENABLE_FEATURE") != "true" {
snaps.Skip(t, "Feature not enabled")
}
// Test code here
snaps.MatchSnapshot(t, someValue)
}
```
--------------------------------
### Snapshotting JSON with Any Matcher
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneJSON.md
This example shows how to use the `match.Any` matcher to ignore specific fields like timestamps or request IDs during JSON snapshot comparison. This is useful when these fields change with each execution.
```go
func TestAPIWithMatcher(t *testing.T) {
resp := map[string]any{
"status": "success",
"timestamp": time.Now(),
"requestId": "req-1234",
}
snaps.MatchStandaloneJSON(
t,
resp,
match.Any("timestamp", "requestId"),
)
}
```
--------------------------------
### Configure Snapshot Directory with Absolute Path
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/configuration.md
When using the -trimpath flag, ensure snapshot paths are absolute. This example uses snaps.Dir with an absolute path, potentially read from an environment variable.
```go
snaps.WithConfig(snaps.Dir("/absolute/path/snapshots")).
MatchSnapshot(t, value)
```
--------------------------------
### Interpreting Diff Output in Go-Snaps
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/errors.md
Provides an example of the diff output format when a snapshot mismatch occurs, explaining the meaning of '-' (removed lines) and '+' (added lines), and indicating the file path and line number of the snapshot.
```text
Snapshot - 5
Received + 2
- expected value content
+ actual value content
at __snapshots__/test_file.snap:25
```
--------------------------------
### TestMain Preserving Test Result with Dirty Check
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Clean.md
This example demonstrates how to use Clean in TestMain and ensure the program exits with a non-zero code if tests failed OR if snapshots are dirty, preventing merging of outdated snapshots.
```go
func TestMain(m *testing.M) {
v := m.Run()
dirty, err := snaps.Clean(m)
if err != nil {
fmt.Println("Cleanup error:", err)
os.Exit(1)
}
// Exit with non-zero if tests failed OR snapshots are dirty
exitCode := v
if dirty {
exitCode = 1
}
os.Exit(exitCode)
}
```
--------------------------------
### Method Chaining with Multiple Configurations
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Shows how to chain multiple configuration options, like filename and extension, before matching standalone JSON data.
```go
snaps.WithConfig(
snaps.Filename("api_responses"),
snaps.Ext(".json"),
).MatchStandaloneJSON(t, apiData)
```
--------------------------------
### Custom Array Item Validation
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Matchers.md
Validates that each item in an array starts with 'uuid-', replacing them with '' in the snapshot.
```go
func TestArrayItems(t *testing.T) {
data := map[string]any{
"ids": []any{"uuid-1", "uuid-2", "uuid-3"},
}
snaps.MatchJSON(
t,
data,
match.Custom("ids.#", func(val any) (any, error) {
id, ok := val.(string)
if !ok {
return nil, fmt.Errorf("expected string id")
}
if !strings.HasPrefix(id, "uuid-") {
return nil, fmt.Errorf("invalid uuid format")
}
return "", nil
}),
)
}
```
--------------------------------
### Skip Sub-Tests Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Demonstrates skipping a sub-test within a test suite using snaps.Skip when a feature is not enabled.
```go
func TestSuite(t *testing.T) {
t.Run("enabled-feature", func(t *testing.T) {
snaps.MatchSnapshot(t, "test")
})
t.Run("disabled-feature", func(t *testing.T) {
if !featureEnabled {
snaps.Skip(t)
}
snaps.MatchSnapshot(t, "skipped")
})
}
```
--------------------------------
### Standalone Snapshot with Custom Extension
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Use MatchStandaloneSnapshot to create individual snapshot files. Combine with snaps.Ext to specify file extensions for syntax highlighting.
```go
// test_simple.go
func TestSimple(t *testing.T) {
snaps.MatchStandaloneSnapshot(t, "Hello World")
// or create an html snapshot file
snaps.WithConfig(snaps.Ext(".html")).
MatchStandaloneSnapshot(t, "Hello World
")
}
```
--------------------------------
### Basic Configuration with Dir
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Applies a custom directory for storing snapshots. Use this when you need to organize snapshots separately from the test files.
```go
snaps.WithConfig(snaps.Dir("__snapshots__")).MatchSnapshot(t, value)
```
--------------------------------
### Method Chaining with WithConfig
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Demonstrates chaining snapshot matching methods after configuring the snapshot directory.
```go
snaps.WithConfig(snaps.Dir("custom")),
.MatchSnapshot(t, value)
```
--------------------------------
### Using the Any Matcher for Placeholders
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Illustrates how to use the `match.Any` matcher to replace specific paths with a placeholder. It can be configured with a custom placeholder value and error handling for missing paths.
```go
Any("user.name")
// or with multiple paths
Any("user.name", "user.email")
// or with a attribute of a object in array
Any("#.name")
```
```go
match.Any("user.name").
Placeholder(value). // allows to define a different placeholder value from the default ""
ErrOnMissingPath(bool) // determines whether the matcher will err in case of a missing, default true
```
--------------------------------
### Simple Value Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchSnapshot.md
Demonstrates capturing a single string value as a snapshot. Ensure the 'snaps' package is imported.
```go
func TestSimpleValue(t *testing.T) {
snaps.MatchSnapshot(t, "Hello World")
}
```
--------------------------------
### Snapshotting a Configuration File
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneYAML.md
Illustrates capturing a complex, nested configuration structure as a YAML snapshot. The input can be any Go type that can be marshaled into YAML.
```go
func TestConfigFile(t *testing.T) {
config := map[string]any{
"server": map[string]any{
"host": "localhost",
"port": 8080,
},
"database": map[string]any{
"driver": "postgres",
"url": "postgres://localhost/db",
},
}
snaps.MatchStandaloneYAML(t, config)
}
```
--------------------------------
### Multiple Configuration Options
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Combines several configuration options to customize snapshot storage and update behavior. This is useful for setting up specific snapshot environments for a test.
```go
snaps.WithConfig(
snaps.Dir("snapshots"),
snaps.Filename("custom"),
snaps.Update(true),
).MatchSnapshot(t, value)
```
--------------------------------
### Go: Match.Custom Validation Failed
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/errors.md
This example shows a validation failure from a custom callback in match.Custom. Ensure the data conforms to the expected type or update the callback logic.
```go
func TestCustomError(t *testing.T) {
data := map[string]any{"age": "not a number"}
snaps.MatchJSON(
t,
data,
match.Custom("age", func(val any) (any, error) {
age, ok := val.(float64)
if !ok {
return nil, fmt.Errorf("expected number but got %T", val)
}
return "valid", nil
}),
// Error: match.Custom("age") - expected number but got string
)
}
```
--------------------------------
### Basic Standalone YAML Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneYAML.md
Demonstrates a basic usage of MatchStandaloneYAML with a simple YAML string. This will create a new snapshot file named `TestStandaloneYAML_1.snap.yaml` in the `__snapshots__` directory.
```go
func TestStandaloneYAML(t *testing.T) {
snaps.MatchStandaloneYAML(t, "user: alice\nage: 30\nemail: alice@example.com")
// Creates __snapshots__/TestStandaloneYAML_1.snap.yaml
}
```
--------------------------------
### Go: Match Invalid YAML
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/errors.md
This example demonstrates an error when invalid YAML is provided to MatchYAML. Validate the YAML syntax before passing it or use YAML marshaling for structs.
```go
func TestInvalidYAML(t *testing.T) {
snaps.MatchYAML(t, "{ invalid yaml [")
// Error: invalid yaml:
}
```
--------------------------------
### Solution with snaps.Skip
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Shows how `snaps.Skip` resolves the obsolescence issue by tracking skipped tests, ensuring their snapshots are correctly excluded from `Clean` operations.
```go
func TestFeature(t *testing.T) {
if os.Getenv("SKIP_ME") != "" {
snaps.Skip(t, "Skipping") // <-- snaps.Skip tracks the skip
}
snaps.MatchSnapshot(t, value)
}
```
--------------------------------
### Conditional Snapshot Updates
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Controls whether snapshots can be updated based on a boolean condition. This allows for dynamic update behavior, for example, only updating snapshots during local development.
```go
snaps.WithConfig(
snaps.Update(shouldUpdate), // true/false based on some condition
).MatchSnapshot(t, value)
```
--------------------------------
### Default Configuration Structure
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/configuration.md
Illustrates the default configuration struct used by go-snaps when no explicit configuration is provided. It includes default snapshot directory and how the update behavior respects environment variables.
```go
defaultConfig = Config{
snapsDir: "__snapshots__",
// filename: derived from test file
// extension: ""
// update: nil (respects env var)
// json: nil (uses defaults)
// serializer: nil (uses pretty printer)
}
```
--------------------------------
### Go-Snaps Package Structure
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/README.md
Illustrates the directory structure of the Go-Snaps library, showing the main packages and their purposes.
```go
github.com/gkampitakis/go-snaps
├── snaps - Main snapshot matching package
│ ├── MatchSnapshot variants
│ ├── Configuration functions
│ └── Test utilities (Clean, Skip, etc.)
├── match - Field matchers for JSON/YAML
│ ├── Any matcher
│ ├── Custom matcher
│ └── Type matcher
└── internal - Internal utilities
├── colors - Terminal output coloring
├── difflib - Diff generation
└── test - Test utilities
```
--------------------------------
### Skip External Service Tests Example
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Conditionally skip tests that rely on external services if the service is unavailable. snaps.Skipf provides a formatted message indicating the service endpoint.
```go
func TestExternalAPI(t *testing.T) {
if !externalServiceAvailable() {
snaps.Skipf(t, "External service unavailable: %s", os.Getenv("API_ENDPOINT"))
}
resp := callExternalAPI()
snaps.MatchJSON(t, resp)
}
```
--------------------------------
### Go-Snaps Import Paths
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/README.md
Shows the necessary import paths for using the main snapshot matching and field matcher packages in your Go project.
```go
// Main snapshot matching
"github.com/gkampitakis/go-snaps/snaps"
// Field matchers
"github.com/gkampitakis/go-snaps/match"
```
--------------------------------
### Configure Snapshot Matching with Custom Options
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Use WithConfig to apply custom configurations like filename, directory, extension, update behavior, custom serializers, or JSON formatting before matching a snapshot.
```go
t.Run("snapshot tests", func(t *testing.T) {
snaps.WithConfig(snaps.Filename("my_custom_name"), snaps.Dir("my_dir")).MatchSnapshot(t, "Hello Word")
s := snaps.WithConfig(
snaps.Dir("my_dir"),
snaps.Filename("json_file"),
snaps.Ext(".json"),
snaps.Update(false),
snaps.Serializer(func(v any) string {
// custom serializer logic
return fmt.Sprintf("custom: %v", v)
}),
// or snaps.Raw() for no formatting
snaps.JSON(snaps.JSONConfig{
Width: 80,
Indent: " ",
SortKeys: false,
}),
)
s.MatchJSON(t, `{"hello":"world"}`)
})
```
--------------------------------
### Create Inline Snapshots
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
On the first run, pass nil as the last argument to MatchInlineSnapshot to create the snapshot. Subsequent runs will compare against the generated inline snapshot.
```go
func TestInlineSnapshot(t *testing.T) {
snaps.MatchInlineSnapshot(t, "Hello World", nil)
snaps.MatchInlineSnapshot(t, 123, nil)
snaps.MatchInlineSnapshot(t, map[string]int{"foo": 1, "bar": 2}, nil)
}
```
--------------------------------
### Array Elements with Any Matcher
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Matchers.md
Apply the Any matcher to elements within an array in JSON snapshots by using array index notation or '#' for all elements. This example targets all 'id' fields within the 'users' array.
```go
func TestArrayWithAny(t *testing.T) {
data := map[string]any{
"users": []map[string]any{
{"id": "1", "name": "Alice"},
{"id": "2", "name": "Bob"},
},
}
snaps.MatchJSON(
t,
data,
match.Any("users.#.id"), // All IDs in users array
)
}
```
--------------------------------
### Go: Match Snapshot Mismatch
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/errors.md
This example shows a snapshot mismatch where the actual value differs from the stored snapshot. Review the diff and update the snapshot if the change is intentional, or fix the code if it's unintentional.
```go
// Snapshot stored: "Hello World"
func TestMismatch(t *testing.T) {
snaps.MatchSnapshot(t, "Hello Universe")
// Error: value doesn't match snapshot
// Diff shows:
// - Hello World
// + Hello Universe
}
```
--------------------------------
### First Run Workflow: Initial Test Code
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
The initial state of the test code before the first snapshot generation. `nil` is passed for the expected snapshot value.
```go
func TestAPI(t *testing.T) {
result := someFunction()
snaps.MatchInlineSnapshot(t, result, nil) // Pass nil initially
}
```
--------------------------------
### HTML Snapshot with Syntax Highlighting
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneSnapshot.md
Configure `MatchStandaloneSnapshot` with a `.html` extension to generate snapshots that support HTML syntax highlighting in editors. This is useful for capturing HTML output directly.
```go
func TestHTMLRendering(t *testing.T) {
html := `
Hello
`
snaps.WithConfig(snaps.Ext(".html")),
MatchStandaloneSnapshot(t, html)
}
```
--------------------------------
### Customizing Snapshot Directory and Serializer
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneYAML.md
Configures MatchStandaloneYAML to use a custom directory (`fixtures/yaml`) for snapshots and a raw serializer (`fmt.Sprint`) instead of pretty-printing. This allows for more control over snapshot storage and formatting.
```go
func TestCustomConfig(t *testing.T) {
snaps.WithConfig(
snaps.Dir("fixtures/yaml"),
snaps.Raw(), // Use fmt.Sprint instead of pretty printing
).MatchStandaloneYAML(t, map[string]string{"key": "value"})
// Creates fixtures/yaml/TestCustomConfig_1.snap.yaml
}
```
--------------------------------
### MatchStandaloneYAML with String and Struct
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Shows how to use MatchStandaloneYAML to create separate snapshot files for YAML data from string and struct inputs. Snapshots are saved in the `__snapshots__` directory.
```go
func TestSimple(t *testing.T) {
snaps.MatchStandaloneYAML(t, "user: \"mock-user\"
age: 10
email: \"mock@email.com\"")
snaps.MatchStandaloneYAML(t, User{10, "mock-email"})
}
```
--------------------------------
### Basic Standalone Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneSnapshot.md
Use this snippet to create a single, standalone snapshot file for a given input. The snapshot will be stored in the default `__snapshots__` directory with an incrementing file name.
```go
func TestStandalone(t *testing.T) {
snaps.MatchStandaloneSnapshot(t, "Hello World")
// Creates __snapshots__/TestStandalone_1.snap
}
```
--------------------------------
### Snapshotting Complex Nested JSON with Matchers
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneJSON.md
This example illustrates snapshotting a deeply nested JSON structure that includes arrays of objects. It utilizes `match.Any` to ignore dynamic fields like timestamps within the nested elements.
```go
func TestComplexJSON(t *testing.T) {
data := map[string]any{
"users": []map[string]any{
{
"id": "user-1",
"name": "Alice",
"created": time.Now(),
},
{
"id": "user-2",
"name": "Bob",
"created": time.Now(),
},
},
}
snaps.MatchStandaloneJSON(
t,
data,
match.Any("users.#.id", "users.#.created"),
)
}
```
--------------------------------
### First Run: Generate Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
On the first run, call MatchInlineSnapshot with nil as the expected value to generate the snapshot.
```go
snaps.MatchInlineSnapshot(t, "Hello World", nil)
```
--------------------------------
### Complex Configuration for YAML Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Combines directory, filename, and extension settings for creating YAML snapshots. This is useful for structured data that needs to be snapshotted in YAML format.
```go
snaps.WithConfig(
snaps.Dir("test_fixtures"),
snaps.Filename("config"),
snaps.Ext(".yaml"),
).MatchStandaloneYAML(t, yamlData)
```
--------------------------------
### Basic YAML Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchYAML.md
Use this snippet to create a basic YAML snapshot from a string. Ensure the input string is valid YAML.
```go
func TestYAML(t *testing.T) {
snaps.MatchYAML(t, "user: alice\nage: 30\nemail: alice@example.com")
}
```
--------------------------------
### Go-Snaps File Structure
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/00-START-HERE.md
This snippet shows the directory structure of the Go-Snaps project, highlighting the location of the main documentation files.
```bash
.
├── 00-START-HERE.md 👈 You are here
├── INDEX.md 📍 Navigation & index
├── README.md 📖 Overview & quick reference
├── types.md 🔧 Type definitions
├── configuration.md ⚙️ Configuration options
├── errors.md 🚨 Error handling
└── api-reference/ 📚 API documentation
├── MatchSnapshot.md
├── MatchStandaloneSnapshot.md
├── MatchJSON.md
├── MatchStandaloneJSON.md
├── MatchYAML.md
├── MatchStandaloneYAML.md
├── MatchInlineSnapshot.md
├── WithConfig.md
├── Clean.md
├── Skip.md
└── Matchers.md
```
--------------------------------
### Custom Directory and Extension for Standalone Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Configures a specific directory and file extension for a standalone snapshot, suitable for non-Go data like HTML content. Ensure the extension matches the content type.
```go
snaps.WithConfig(
snaps.Dir("fixtures"),
snaps.Ext(".html"),
).MatchStandaloneSnapshot(t, htmlContent)
```
--------------------------------
### WithConfig
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/WithConfig.md
Creates a new Config instance with custom options and returns it for chaining with snapshot matching methods. It provides a builder pattern for configuring snapshot behavior.
```APIDOC
## WithConfig
### Description
Creates a new Config instance with custom options and returns it for chaining with snapshot matching methods. It provides a builder pattern for configuring snapshot behavior.
### Function Signature
```go
func WithConfig(args ...func(*Config)) *Config
```
### Parameters
#### Variadic Parameters
- **args** (...func(*Config)) - Optional - Variable number of configuration option functions to apply to the config.
### Return Type
- **`*Config`**: A configured Config instance that can call snapshot matching methods.
### Configuration Options
All configuration options are functions that modify a Config pointer. Common options include:
- **Dir(path string)**: Set snapshot directory path.
- **Filename(name string)**: Set snapshot filename.
- **Ext(ext string)**: Set snapshot file extension.
- **Update(bool)**: Control snapshot update behavior.
- **Serializer(func)**: Set custom value serializer.
- **Raw()**: Use `fmt.Sprint` for serialization.
- **JSON(JSONConfig)**: Configure JSON formatting.
### Behavior
- Creates a new Config instance from the default config.
- Applies all provided configuration functions in order.
- Returns the configured instance for method chaining.
- Configuration is isolated to this instance; doesn't affect other tests.
- Each option function receives a pointer and modifies it in place.
### Usage Examples
#### Basic Configuration
```go
snaps.WithConfig(snaps.Dir("__snapshots__")).MatchSnapshot(t, value)
```
#### Multiple Configuration Options
```go
snaps.WithConfig(
snaps.Dir("snapshots"),
snaps.Filename("custom"),
snaps.Update(true),
).MatchSnapshot(t, value)
```
#### Custom Directory and Extension
```go
snaps.WithConfig(
snaps.Dir("fixtures"),
snaps.Ext(".html"),
).MatchStandaloneSnapshot(t, htmlContent)
```
#### JSON-Specific Configuration
```go
snaps.WithConfig(
snaps.JSON(snaps.JSONConfig{
Width: 120,
Indent: " ",
SortKeys: false,
}),
).MatchJSON(t, jsonData)
```
#### Raw Serialization
```go
snaps.WithConfig(snaps.Raw()).MatchSnapshot(t, complexValue)
// Serializes using fmt.Sprint without pretty-printing
```
#### Custom Serializer Function
```go
snaps.WithConfig(
snaps.Serializer(func(v any) string {
// Custom serialization logic
return fmt.Sprintf("[custom] %v", v)
}),
).MatchSnapshot(t, value)
```
#### Conditional Updates
```go
snaps.WithConfig(
snaps.Update(shouldUpdate), // true/false based on some condition
).MatchSnapshot(t, value)
```
#### Absolute Path Configuration
```go
snaps.WithConfig(
snaps.Dir("/absolute/path/to/snapshots"),
).MatchSnapshot(t, value)
```
#### Complex Configuration with YAML
```go
snaps.WithConfig(
snaps.Dir("test_fixtures"),
snaps.Filename("config"),
snaps.Ext(".yaml"),
).MatchStandaloneYAML(t, yamlData)
```
#### Override with Environment Variable
```go
// Respects UPDATE_SNAPS env var even with Update(false)
snaps.WithConfig(snaps.Update(false)).MatchSnapshot(t, value)
```
```
--------------------------------
### Using Absolute Paths with -trimpath
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/configuration.md
Provides a solution for using the `go test -trimpath` flag by configuring snapshots with an absolute path, typically read from an environment variable.
```go
snaps.WithConfig(snaps.Dir(os.Getenv("SNAP_DIR"))).MatchSnapshot(t, value)
```
--------------------------------
### Basic Inline Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchInlineSnapshot.md
Use this for simple string values without special characters.
```go
snaps.Inline("value")
```
--------------------------------
### Organize Snapshots by File Type and Directory
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/README.md
Configure snapshot matching to use a specific directory and file extension. This helps in organizing snapshots, especially for different data formats like JSON.
```go
snaps.WithConfig(
snaps.Dir("snapshots/json"),
snaps.Ext(".json"),
).MatchStandaloneJSON(t, data)
```
--------------------------------
### MatchYAML with String, Byte Slice, and Struct
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Demonstrates using MatchYAML to capture YAML data from string, byte slice, and struct inputs. Ensure the input can be marshaled to YAML.
```go
func TestYAML(t *testing.T) {
type User struct {
Age int
Email string
}
snaps.MatchYAML(t, "user: \"mock-user\"
age: 10
email: mock@email.com")
snaps.MatchYAML(t, []byte("user: \"mock-user\"
age: 10
email: mock@email.com"))
snaps.MatchYAML(t, User{10, "mock-email"})
}
```
--------------------------------
### Problem with standard testing.Skip
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/Skip.md
Illustrates the issue with the standard `testing.Skip` where `Clean()` may incorrectly mark snapshots as obsolete because go-snaps is unaware of the skip.
```go
func TestFeature(t *testing.T) {
if os.Getenv("SKIP_ME") != "" {
t.Skip("Skipping") // <-- Standard skip
}
snaps.MatchSnapshot(t, value)
}
```
--------------------------------
### Using Matchers for Dynamic Fields
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneYAML.md
Demonstrates how to use `match.Any` to ignore or standardize dynamic fields like timestamps or IDs during snapshot comparison. This ensures snapshots are stable even when certain values change.
```go
func TestConfigWithMatcher(t *testing.T) {
config := map[string]any{
"generated_at": time.Now(),
"version": "1.0.0",
"api_key": "secret-key-1234",
}
snaps.MatchStandaloneYAML(
t,
config,
match.Any("$.generated_at", "$.api_key"),
)
}
```
--------------------------------
### Multiple YAML Snapshots in One Test
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneYAML.md
Shows how to create multiple, distinct YAML snapshots within a single test function. Each call to MatchStandaloneYAML generates a new, auto-incremented snapshot file (e.g., `TestMultipleYAML_1.snap.yaml`, `TestMultipleYAML_2.snap.yaml`).
```go
func TestMultipleYAML(t *testing.T) {
config1 := map[string]any{"database": "postgres", "port": 5432}
snaps.MatchStandaloneYAML(t, config1)
// Creates TestMultipleYAML_1.snap.yaml
config2 := map[string]any{"cache": "redis", "ttl": 3600}
snaps.MatchStandaloneYAML(t, config2)
// Creates TestMultipleYAML_2.snap.yaml
}
```
--------------------------------
### Snapshot with Any Matcher for Dynamic Fields
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchJSON.md
Use the `match.Any` matcher to replace specific fields with a placeholder, useful for dynamic data like timestamps or IDs.
```go
func TestWithDynamicFields(t *testing.T) {
data := map[string]any{
"user": "alice",
"id": "uuid-1234",
"created": time.Now().String(),
}
snaps.MatchJSON(
t,
data,
match.Any("id", "created"), // Replace these fields with placeholder
)
}
```
--------------------------------
### Create New Snapshots
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/README.md
Command to create new snapshots for all tests in the project. Ensure the UPDATE_SNAPS environment variable is set to 'true'.
```bash
UPDATE_SNAPS=true go test ./...
```
--------------------------------
### Setting Environment Variable for -trimpath
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/configuration.md
Demonstrates how to set the SNAP_DIR environment variable to specify the absolute path for snapshots when using `go test -trimpath`.
```bash
SNAP_DIR=/absolute/path go test -trimpath ./...
```
--------------------------------
### Standalone JSON Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Use MatchStandaloneJSON to create individual JSON snapshot files. The filenames include the test name and a number, with a .snap.json extension.
```go
func TestSimple(t *testing.T) {
snaps.MatchStandaloneJSON(t, `{"user":"mock-user","age":10,"email":"mock@email.com"}`)
snaps.MatchStandaloneJSON(t, User{10, "mock-email"})
}
```
--------------------------------
### API Response Testing with Custom JSON Formatting
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/configuration.md
Configures snapshotting for API responses, specifying a directory, filename, and custom JSON formatting including width, indentation, and key sorting.
```go
snaps.WithConfig(
snaps.Dir("fixtures/responses"),
snaps.Filename("api_responses"),
snaps.JSON(snaps.JSONConfig{
Width: 200,
Indent: " ",
SortKeys: true,
}),
).MatchStandaloneJSON(t, apiResponse)
```
--------------------------------
### Absolute Path Resolution
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/configuration.md
Shows how absolute paths provided to snaps.Dir are used directly, creating snapshots at the specified root location regardless of the test file's path.
```go
snaps.WithConfig(snaps.Dir("/tmp/snaps")).MatchSnapshot(t, value)
// Creates: /tmp/snaps/test_file.snap
```
--------------------------------
### Basic Snapshot Test
Source: https://github.com/gkampitakis/go-snaps/blob/main/README.md
Use MatchSnapshot to capture string data in a test. Snapshots are saved in the __snapshots__ directory.
```go
package example
import (
"testing"
"github.com/gkampitakis/go-snaps/snaps"
)
func TestExample(t *testing.T) {
snaps.MatchSnapshot(t, "Hello World")
}
```
--------------------------------
### Basic JSON Snapshot
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchJSON.md
Use this snippet to create a basic JSON snapshot of a string. Ensure the input string is valid JSON.
```go
func TestJSON(t *testing.T) {
snaps.MatchJSON(t, `{"user":"alice","age":30}`)
}
```
--------------------------------
### Snapshotting JSON to a Custom Directory
Source: https://github.com/gkampitakis/go-snaps/blob/main/_autodocs/api-reference/MatchStandaloneJSON.md
This snippet demonstrates how to specify a custom directory for storing snapshot files using `snaps.Dir()`. This allows for better organization of snapshots, especially in larger projects.
```go
func TestCustomDirectory(t *testing.T) {
snaps.WithConfig(snaps.Dir("fixtures/json")),
.MatchStandaloneJSON(t, map[string]string{"test": "data"})
// Creates fixtures/json/TestCustomDirectory_1.snap.json
}
```