gkampitakis/go-snaps

[Feature Request ]: support gomock matcher

Closed this issue ยท 6 comments

picone commented

๐Ÿš€ Feature Proposal

I have tried to wrote a test.Matcher implement, but the snapDirAndName getting the real path by the caller. So I have to implement my matcher in each package to ensure that the save path of the snaps are correct.

So is there a way to replace the path? I thought it would be possible to add an option to modify the skip number of baseCaller

Motivation

Match json data in gomock arguments.

Example

myStub.EXPECT().DoSomething(mysnaps.MatchJSON())

Hey ๐Ÿ‘‹ . Thanks a lot for this issue. Could you help me with a reproducible example or more details about your use case ? ( i am not really familiar with the go mock ). I am interested on supporting this use case ( better ?? ) just trying to understand how would that work.

picone commented

Here is a example for the gomock:

func TestHello(t *testing.T) {
  t.Run("some test", func(t *testing.T) {
    ctrl := gomock.NewController(t)

    myStub := NewMockHello(ctrl)
    myStub.EXPECT().DoSomething(gomock.Eq("A"), gomock.Any()).Returns(xxx)
  })
}

myStub will replace the original function implementation, and the function in my code will call myStub.DomeSomething("A", "B"). I need to confirm whether the second argument is "B" instead of using gomock.Any(), so that I need to write myStub.EXPECT().DoSomething(gomock.Eq("A"), gomock.Eq("B")) in my test.
This is the simplest case, but if the argument become complex, I need to snaps it and assert it.
So I wrap a simple gomock.Matcher:

var _ gomock.Matcher = (*mySnaps)(nil)
type mySnaps struct {
  t *testing.T
}

func (s mySnaps) Matches(data any) bool {
  snaps.MatchSnapshot(s.t, data)
  return true
}

func (s mySnaps) String() string {
  return "my-snaps"
}

That's really clever actually ๐Ÿ˜… .
I did a quick test and this seems to work https://github.com/gkampitakis/go-snaps-go-mock, not sure if i miss something.

picone commented

Cool, I get it. So can this be inherited in go-snaps?

oh okay i misunderstood, so this is not an issue right ?

but the snapDirAndName getting the real path by the caller. So I have to implement my matcher in each package to ensure that the save path of the snaps are correct.

The request is supporting this inside go-snaps?

var _ gomock.Matcher = (*mySnaps)(nil)

type mySnaps struct {
	t *testing.T
}

func EqSnap(t *testing.T) *mySnaps {
	return &mySnaps{t}
}

func (s mySnaps) Matches(data any) bool {
	// this might not be even needed
	s.t.Helper()
	snaps.MatchSnapshot(s.t, data)
	return true
}

func (s mySnaps) String() string {
	return "my-snaps"
}
picone commented

Thanks gkampitakis, I have resolved my issue.