CallRoute executes a request against a registered route and returns the typed response. The request body is JSON-encoded from req, and the response is unmarshaled into Res. This is the primary way to test API endpoints. Pass nil headers to use an empty header set.
(h *Harness, route zen.Route, headers http.Header, req Req)
| 652 | // into Res. This is the primary way to test API endpoints. Pass nil headers to use |
| 653 | // an empty header set. |
| 654 | func CallRoute[Req any, Res any](h *Harness, route zen.Route, headers http.Header, req Req) TestResponse[Res] { |
| 655 | h.t.Helper() |
| 656 | |
| 657 | rr := httptest.NewRecorder() |
| 658 | |
| 659 | body := new(bytes.Buffer) |
| 660 | err := json.NewEncoder(body).Encode(req) |
| 661 | require.NoError(h.t, err) |
| 662 | |
| 663 | httpReq := httptest.NewRequest(route.Method(), route.Path(), body) |
| 664 | httpReq.Header = headers |
| 665 | if httpReq.Header == nil { |
| 666 | httpReq.Header = http.Header{} |
| 667 | } |
| 668 | |
| 669 | h.srv.Mux().ServeHTTP(rr, httpReq) |
| 670 | require.NoError(h.t, err) |
| 671 | |
| 672 | rawBody := rr.Body.Bytes() |
| 673 | |
| 674 | res := TestResponse[Res]{ |
| 675 | Status: rr.Code, |
| 676 | Headers: rr.Header(), |
| 677 | RawBody: string(rawBody), |
| 678 | Body: nil, |
| 679 | } |
| 680 | |
| 681 | var responseBody Res |
| 682 | err = json.Unmarshal(rawBody, &responseBody) |
| 683 | require.NoError(h.t, err) |
| 684 | |
| 685 | res.Body = &responseBody |
| 686 | |
| 687 | return res |
| 688 | } |
| 689 | |
| 690 | // UnmarshalBody decodes a JSON response body into the provided pointer. This is |
| 691 | // useful when working directly with httptest.ResponseRecorder rather than using |