Documentation ¶
Overview ¶
Package snap provides a simple implementation of Snapshot testing in Go.
The Snap function provides the ability for diffing with other strings, and can update it's own source code to match the expected value.
Usage:
func TestAddition(t *testing.T) { checkAddition := func(x int, y int, want *snap.Snapshot) { got := x + y want.Diff(strconv.Itoa(got)) } checkAddition(2, 2, snap.Snap(t, "8")) // should be 4 }
Running that test will fail, printing the diff between the actual result (`4`) and what is specified in the source code:
snap_test.go:34: snap: Snapshot differs: (-want +got): string( - "8", + "4", ) snap_test.go:34: snap: Rerun with SNAP_UPDATE=1 environmental variable to update the snapshot. --- FAIL: TestAddition (0.00s)
Re-running the test with SNAP_UPDATE=1 environmental variable will update the source code in-place to say "4". Alternatively, you can use Snapshot.Update to auto-update just a single test.
Snapshots can use the `<snap:ignore>` marker to ignore part of input. This is helpful when dealing with values that change between test runs, like timestamps:
func TestSnapTime(t *testing.T) { timestampStr := fmt.Sprintf("Unix time is %d ms", time.Now().UnixMilli()) snap.Snap(t, "Unix time is <snap:ignore> ms").Diff(timestampStr) }
Main idea and influence came from these articles:
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
func Snap ¶
Creates a new Snapshot.
Set SNAP_UPDATE=1 environment variable or call the Snapshot.Update method to automagically update the test value.
func (*Snapshot) Diff ¶
Diff compares the snapshot with a given string. It calls testing.T.Error when the snapshot is not equal to the value or when an error is encountered elsewhere.
func (*Snapshot) DiffJSON ¶
DiffJSON compares the snapshot with the json serialization of a value. It calls testing.T.Error when the snapshot is not equal to the value or when an error is encountered elsewhere.