When testing Chi routes that rely on path variables, it's crucial to mimic the access to these variables in tests. Initially, you may encounter an "Unprocessable Entity" error due to the path variable not being available to the context accessed in the test.
To resolve this issue, manually add the path parameters to the request context before executing the handler under test. Here's an example:
<code class="go">package main import ( "context" "fmt" "net/http" "net/http/httptest" "testing" "github.com/go-chi/chi" ) type ctxKey struct { name string } func TestGetArticleID(t *testing.T) { tests := []struct { name string rec *httptest.ResponseRecorder req *http.Request expectedBody string expectedHeader string }{ { name: "OK_1", rec: httptest.NewRecorder(), req: httptest.NewRequest("GET", "/articles/1", nil), expectedBody: `article ID:1`, }, { name: "OK_100", rec: httptest.NewRecorder(), req: httptest.NewRequest("GET", "/articles/100", nil), expectedBody: `article ID:100`, }, { name: "BAD_REQUEST", rec: httptest.NewRecorder(), req: httptest.NewRequest("PUT", "/articles/bad", nil), expectedBody: fmt.Sprintf("%s\n", http.StatusText(http.StatusBadRequest)), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { // Manually add the path variable to the request context rctx := chi.NewRouteContext() rctx.URLParams.Add("articleID", test.req.URL.Path[len("/articles/"):]) test.req = test.req.WithContext(context.WithValue(test.req.Context(), chi.RouteCtxKey, rctx)) ArticleCtx(http.HandlerFunc(GetArticleID)).ServeHTTP(test.rec, test.req) if test.expectedBody != test.rec.Body.String() { t.Errorf("Got: \t\t%s\n\tExpected: \t%s\n", test.rec.Body.String(), test.expectedBody) } }) } }</code>
This modification allows the test to access the path variable through the context, resolving the "Unprocessable Entity" error.
The above is the detailed content of How to Access Path Variables in Chi Routes for Unit Tests?. For more information, please follow other related articles on the PHP Chinese website!