Skip to content

Commit 693e3cf

Browse files
committed
Add matchers for gomega assertion library
1 parent db4af89 commit 693e3cf

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

testing/matchers/package.go

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Package matchers contain matchers for use with the [gomega] assertion library.
2+
package matchers
3+
4+
import (
5+
"bytes"
6+
7+
"github.com/gost-dom/generators"
8+
"github.com/onsi/gomega"
9+
"github.com/onsi/gomega/types"
10+
)
11+
12+
func render(g generators.Generator) (string, error) {
13+
var b bytes.Buffer
14+
err := g.Generate().Render(&b)
15+
return b.String(), err
16+
}
17+
18+
// HaveRendered returns a [types.GomegaMatcher] that matches string rendered
19+
// statement against another GomegaMatcher. If the expected value is not a
20+
// GomegaMatcher, it will implicitly match for equality using [gomega.Equal].
21+
func HaveRendered(expected interface{}) types.GomegaMatcher {
22+
matcher, ok := expected.(types.GomegaMatcher)
23+
if !ok {
24+
return HaveRendered(gomega.Equal(expected))
25+
}
26+
return gomega.WithTransform(render, matcher)
27+
}
28+
29+
// HaveRenderedSubstring is simple helper for [HaveRendered] for a very common
30+
// use case to test for the presence of a substrubg in the rendered statement.
31+
// Short for HaveRendered(gomega.ContainSubstring(expected)).
32+
func HaveRenderedSubstring(expected string) types.GomegaMatcher {
33+
return HaveRendered(gomega.ContainSubstring(expected))
34+
}

testing/matchers/package_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package matchers_test
2+
3+
import (
4+
"testing"
5+
6+
gen "github.com/gost-dom/generators"
7+
. "github.com/gost-dom/generators/testing/matchers"
8+
9+
"github.com/onsi/gomega"
10+
)
11+
12+
func TestHaveRendered(t *testing.T) {
13+
g := gomega.NewWithT(t)
14+
x := gen.NewValue("x")
15+
expr := gen.Assign(x, gen.Lit(42))
16+
g.Expect(HaveRendered("x := 42").Match(expr)).To(gomega.BeTrue())
17+
g.Expect(HaveRendered("y := 42").Match(expr)).To(gomega.BeFalse())
18+
g.Expect(HaveRendered("x := 43").Match(expr)).To(gomega.BeFalse())
19+
20+
compoundExpr := gen.StatementList(expr, gen.Return(x.Field("String").Call()))
21+
g.Expect(HaveRendered("x := 42").Match(compoundExpr)).To(gomega.BeFalse())
22+
g.Expect(HaveRendered("x := 42\nreturn x.String()").Match(compoundExpr)).To(gomega.BeTrue())
23+
g.Expect(HaveRenderedSubstring("x := 42").Match(compoundExpr)).To(gomega.BeTrue())
24+
g.Expect(HaveRendered(gomega.ContainSubstring("x := 42")).Match(compoundExpr)).
25+
To(gomega.BeTrue())
26+
g.Expect(HaveRendered(gomega.MatchRegexp(`x := \d{2}`)).Match(compoundExpr)).
27+
To(gomega.BeTrue())
28+
g.Expect(HaveRendered(gomega.MatchRegexp(`x := \d{3}`)).Match(compoundExpr)).
29+
To(gomega.BeFalse())
30+
}

0 commit comments

Comments
 (0)