From dc9039527b3d7b0e93724d4abce79d3272186f3d Mon Sep 17 00:00:00 2001 From: Yann D'Isanto Date: Thu, 13 Feb 2025 12:18:30 +0100 Subject: [PATCH] fix: mock path with query --- api.go | 2 +- stubs_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/api.go b/api.go index e86d4c3..006d674 100644 --- a/api.go +++ b/api.go @@ -42,7 +42,7 @@ func API(testState TestingT) *APIMock { testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, request *http.Request) { call := HTTPCall{ Method: strings.ToLower(request.Method), - Path: request.RequestURI, + Path: request.URL.Path, } mockedAPI.mu.Lock() diff --git a/stubs_test.go b/stubs_test.go index f14c714..4dc0e76 100644 --- a/stubs_test.go +++ b/stubs_test.go @@ -13,6 +13,11 @@ func (mockedAPI *APIMock) testCall(method, path string, t *testing.T) *httpexpec return e.Request(method, path).Expect() } +func (mockedAPI *APIMock) testCallWithQuery(method, path string, queryObject any, t *testing.T) *httpexpect.Response { + e := httpexpect.Default(t, mockedAPI.GetURL().String()) + return e.Request(method, path).WithQueryObject(queryObject).Expect() +} + func TestApiNotStubbedEndpoint(t *testing.T) { t.Parallel() // Arrange @@ -57,6 +62,38 @@ func TestApiStubbedEndpoint(t *testing.T) { testState.assertDidNotFailed() } +func TestApiStubbedEndpointWithQuery(t *testing.T) { + t.Parallel() + // Arrange + testState := NewTestingMock(t) + mockedAPI := API(testState) + defer func() { mockedAPI.Close() }() + + mockedAPI. + Stub(http.MethodGet, "/endpoint"). + With(func(writer http.ResponseWriter, request *http.Request) { + name := request.FormValue("name") + writer.Header().Add("Content-Type", "text/plain") + writer.WriteHeader(http.StatusCreated) + _, err := writer.Write([]byte("Hello " + name)) + if err != nil { + t.Fatal(err) + } + }) + + query := map[string]any{"name": "John"} + + // Act + call := mockedAPI.testCallWithQuery(http.MethodGet, "/endpoint", query, t) + + // Assert + call. + Status(http.StatusCreated). + Body().IsEqual("Hello John") + + testState.assertDidNotFailed() +} + func TestApiStubbedEndpointWithJson(t *testing.T) { t.Parallel() // Arrange