Skip to content

Commit

Permalink
added unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
gnimnix committed Feb 8, 2024
1 parent 310c656 commit 22a5305
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 2 deletions.
31 changes: 30 additions & 1 deletion src/mocks/authentication/auth_handlers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,33 @@
//src/mocks/authentication/auth_handlers.ts

import { http, HttpResponse } from "msw"
import resolveURL from "../api/fetch.ts";
import resolveURL from "../../api/fetch";


export const mockCSRFToken: string = "SUPERSECRETCSRFTOKEN"
export const mockUsername: string = "testuser"
export const mockPassword: string = "mockpassword"

export const auth_handlers = [
http.post(resolveURL("/auth/csrf"), () => {
return new HttpResponse(null, {
headers: {
'Set-Cookie': mockCSRFToken
}
})
}),

http.post(resolveURL("/auth/login"), async ({ cookies, request }) => {
if (!cookies.csrfmiddlewaretoken) return new HttpResponse(null, {status: 403})
if (cookies.csrfmiddlewaretoken !== mockCSRFToken) return new HttpResponse(null, {status: 403})

const data = await request.formData()
if (data.get("username") !== mockUsername || data.get("password") !== mockPassword) return new HttpResponse(null, {status: 403})

return new HttpResponse(null, {
headers: {
'Set-Cookie': mockCSRFToken
}
})
})
]
9 changes: 8 additions & 1 deletion src/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@
import { http, HttpResponse } from "msw"
import resolveURL from "../api/fetch.ts";

import { auth_handlers } from "./authentication/auth_handlers.ts";

export const handlers = [

const default_handlers = [
http.get(resolveURL('/resource'), () => {
return HttpResponse.json({
result: "Hello World!"
})
})
]


export const handlers = [
...default_handlers,
...auth_handlers
]
23 changes: 23 additions & 0 deletions tests/authentication/auth.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, test } from "vitest"
import { getCSRF, signIn, signOut } from "../../src/api/authentication";
import { mockCSRFToken, mockUsername, mockPassword } from "../../src/mocks/authentication/auth_handlers";

describe("authentication helper functions", () => {

test("should get csrf token", async () => {
const response: Response = await getCSRF()
expect(response.headers).toBe({
'Set-Cookie': mockCSRFToken
})
})

test("should be able to sign in", async () => {
const response = await signIn(mockUsername, mockPassword)
expect(response.status).toBe(200)
})

test("should be able to sign out", async () => {
const response = await signOut()
expect(response.status).toBe(200)
})
})

0 comments on commit 22a5305

Please sign in to comment.