I'm trying to test the Logout handler where there is a ctx.SetCookie method:
func (a *authController) Logout(ctx *gin.Context) {
refreshToken, err := ctx.Cookie("refresh_token")
...
ctx.SetCookie("access_token", "", -1, "/", "localhost", false, true)
ctx.SetCookie("refresh_token", "", -1, "/", "localhost", false, true)
ctx.SetCookie("logged_in", "", -1, "/", "localhost", false, true)
ctx.JSON(http.StatusOK, gin.H{"status": "success"})
}
code inside the test function:
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.SetCookie("logged_in", "truee", 60*60, "/", "localhost", false, false)
req, _ := http.NewRequest("GET", "/logout", nil)
http.SetCookie(recorder, &http.Cookie{Name: "refresh_token", Value: "encodedRefreshToken", MaxAge: 60 * 60, Path: "/", Domain: "localhost", Secure: false, HttpOnly: true}})
http.SetCookie(recorder, &http.Cookie{Name: "access_token", Value: "encodedAccessToken", MaxAge: 60 * 60, Path: "/", Domain: "localhost", Secure: false, HttpOnly: true})
req.Header = http.Header{"Cookie": recorder.Result().Header["Set-Cookie"]}
ctx.Request = req
test.mock()
authController.Logout(ctx)
After the call, I'm trying to check if the cookies have been deleted:
coockies := recorder.Result().Cookies()
for _, c := range coockies {
if c.Name == "access_token" {
assert.Equal(t, "", c.Value)
}
...
}
And I face such a problem that setCookie does not change cookies , but adds new ones . That is, after calling this method, I have two pairs of cookies with access Token, etc.
And as a result, the tests do not pass. I don't understand I'm doing something wrong and can it be solved somehow? or is that how it should be ?