Skip to content

Commit b8efe09

Browse files
committed
cover CORSMiddleware method
1 parent b5a0b14 commit b8efe09

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

middleware_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,47 @@ func TestRouter_Use(t *testing.T) {
3131
t.Errorf("unexpected status code: %d", rec.Code)
3232
}
3333
}
34+
35+
func TestCORSMiddleware(t *testing.T) {
36+
// create a test context
37+
req := httptest.NewRequest("GET", "/test", nil)
38+
w := httptest.NewRecorder()
39+
ctx := NewContext(w, req)
40+
41+
// create a mock handler
42+
mockHandler := func(ctx *Context) error {
43+
return nil
44+
}
45+
46+
// create the CORS middleware
47+
corsMiddleware := CORSMiddleware()
48+
49+
// wrap the mock handler with the CORS middleware
50+
handler := corsMiddleware(mockHandler)
51+
52+
// call the handler with the test context
53+
err := handler(ctx)
54+
55+
// get the http.Response from the ResponseRecorder using Result()
56+
res := w.Result()
57+
58+
// check if the Access-Control-Allow-Origin header was set to "*"
59+
if header := res.Header.Get("Access-Control-Allow-Origin"); header != "*" {
60+
t.Errorf("Expected Access-Control-Allow-Origin header to be \"*\", but got %q", header)
61+
}
62+
63+
// check if the Access-Control-Allow-Methods header was set correctly
64+
if header := res.Header.Get("Access-Control-Allow-Methods"); header != "POST, GET, OPTIONS, PUT, DELETE" {
65+
t.Errorf("Expected Access-Control-Allow-Methods header to be \"POST, GET, OPTIONS, PUT, DELETE\", but got %q", header)
66+
}
67+
68+
// check if the Access-Control-Allow-Headers header was set correctly
69+
if header := res.Header.Get("Access-Control-Allow-Headers"); header != "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization" {
70+
t.Errorf("Expected Access-Control-Allow-Headers header to be \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\", but got %q", header)
71+
}
72+
73+
// check if the handler returned no error
74+
if err != nil {
75+
t.Errorf("Expected handler to return no error, but got %v", err)
76+
}
77+
}

0 commit comments

Comments
 (0)