gkampitakis / go-snaps

Jest-like snapshot testing in Golang 📸
https://pkg.go.dev/github.com/gkampitakis/go-snaps
MIT License
146 stars 6 forks source link

Consider Adding Named Snapshots #88

Open DavidArchibald opened 6 months ago

DavidArchibald commented 6 months ago

🚀 Feature Proposal

A way to substitute the simple incrementing number in snapshot files, e.g. TestName - 1, TestName - 2, etc. with a proper name. I'd be willing to PR this.

Motivation

The clarity of snapshots being named TestName - 1, TestName - 2, and so on can be subpar in the case of a test doing something like this:

func TestFindGoodAndBad(t *testing.T) {
    good, bad := findGoodAndBad(...)

    snaps.MatchSnapshot(t, good)
    snaps.MatchSnapshot(t, bad)
}

I'm aware of the form snaps.MatchSnapshot(t, good, bad) where it'll only create one entry but that version doesn't even indicate where one value starts and the other one ends.

Example

One or multiple of these APIs would be added:

// Useful for consistency with other options
snaps.WithConfig(snaps.Name("foo")).MatchSnapshot(...)

// Useful because it's probably more common to change than other options
snaps.Name("bar").MatchSnapshot(...)

// Useful to be more DRY when reusing the same base configuration multiple time
config := snaps.WithConfig(otherOptions)

config.Name("lorem").MatchSnapshot(...)
config.Name("ipsum").MatchSnapshot(...)

As for how config.Name("foo") being used more than once would work I could go two ways:

  1. It's simply an error to use the same name twice.
  2. An entry named TestName - foo/1 and TestName - foo/2 and so on is generated.
gkampitakis commented 6 months ago

Hey 👋 thanks a lot for taking time creating this issue. Never thought about it, but having a quick look on Jest looks like this is supported. Need to spend some time though to think about the implementation and how it would work and will share my thoughts.

As for the api, I am thinking that config.Name("lorem").MatchSnapshot(...) will introduce yet another way for configuring your snapshots. I know in some places it's not consintent but If I could go back in time I would do some things differently 😅 .

Until that, there is probably the workaround you suggested snaps.MatchSnapshot(t, good, bad) and adding a separator

snaps.MatchSnapshot(t,"\nadding good snapshot\n====\n", good,"\nadding bad snapshot\n====\n", bad)