Skip to content

Commit

Permalink
fix: mock path with query
Browse files Browse the repository at this point in the history
  • Loading branch information
le-yams committed Feb 13, 2025
1 parent 76ddbcf commit dc90395
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
37 changes: 37 additions & 0 deletions stubs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit dc90395

Please sign in to comment.