snapshotter

package module
v0.0.0-...-4b291d6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2022 License: MIT Imports: 8 Imported by: 0

README

Snapshotter

Snapshotter makes it easy to write tests that verify complex test output. To write a snapshot test, make a testhelpers.Snapshotter at the beginning of the test, set up a call to Verify() and call Snapshot(name, value) whenever you want to test a complex output. For example:

func TestWithComplexOutput(t *testing.T) {
    snapshotter := snapshotter.New(t)
    defer snapshotter.Verify()

    output := DoSomethingComplicated()
    snapshotter.Snapshot("complicated", output)
}

After writing the test, you can run it using go test .. However, the test will fail, because the snapshot isn't there yet, with an error like

--- FAIL: TestSnapshotter (0.00s)
    snapshotter.go:89: error reading snapshots: open testdata/TestSnapshotter.snapshots.json: no such file or directory

To generate the snapshots, run go test . -rewriteSnapshots. This generates a set of snapshots files in the testdata directory that should be added to git. Then, the tests will pass. If it at some point a regression causes the test output to break, the snapshotter will catch the changes and fail:

--- FAIL: TestSnapshotter (0.00s)
    snapshotter.go:116: snapshot second differs:
         [
          2,
          {
        -  Foo: "Bar",
        +  Foo: "Foo",
          },
         ]

Happy testing!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Snapshotter

type Snapshotter struct {
	SnapshotErrors bool
	// contains filtered or unexported fields
}

Snapshotter is a utility for writing snapshot tests. In a snapshot, the expected test output is generated by running the test and storing the output, which for complex test outputs would otherwise require a lot of effort to write.

func New

func New(t T) *Snapshotter

New creates a new Snapshotter. Any errors encountered will fail the test.

func NewNamed

func NewNamed(t T, name string) *Snapshotter

func (*Snapshotter) Snapshot

func (s *Snapshotter) Snapshot(name string, values ...interface{})

Snapshot records a value for a snapshot test. For the test to pass, all invocations to Snapshot should have the same arguments. All values should be JSON-marshalable.

func (*Snapshotter) Verify

func (s *Snapshotter) Verify()

Verify finishes a snapshot test. It either compares the test output, or it rewrites the test output.

type T

type T interface {
	Name() string
	Errorf(format string, args ...interface{})
	Helper()
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL