Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(test): core test setup #9238

Merged
merged 8 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ dist
packages/next-auth/providers
packages/next-auth/src/providers/oauth-types.ts
packages/*/*.js
!vite.config.js
packages/*/*.d.ts
packages/*/*.d.ts.map
packages/*/lib
Expand Down
6 changes: 5 additions & 1 deletion packages/core/package.json
ThangHuuVu marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"clean": "rm -rf *.js *.d.ts* lib providers",
"css": "node scripts/generate-css",
"dev": "pnpm css && pnpm providers && tsc -w",
"test": "vitest",
"providers": "node scripts/generate-providers"
},
"devDependencies": {
Expand All @@ -89,7 +90,10 @@
"@types/nodemailer": "6.4.6",
"@types/react": "18.0.37",
"autoprefixer": "10.4.13",
"msw": "^2.0.9",
ThangHuuVu marked this conversation as resolved.
Show resolved Hide resolved
"postcss": "8.4.19",
"postcss-nested": "6.0.0"
"postcss-nested": "6.0.0",
"vite": "^5.0.2",
"vitest": "^0.25.3"
}
}
103 changes: 103 additions & 0 deletions packages/core/src/index.test.ts
ThangHuuVu marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { describe, expect, it, vi } from "vitest"
import { Auth, AuthConfig } from "./index.js"
import GitHub from "./providers/github"
import {
AUTH_SECRET,
SESSION_ACTION,
SESSION_COOKIE_NAME,
} from "./test/constants.js"
import { decode, encode } from "./jwt.js"
import { parse } from "cookie"

const authConfig: AuthConfig = {
providers: [GitHub],
trustHost: true,
secret: AUTH_SECRET,
}

describe("JWT session", () => {
it("should return a valid JWT session response", async () => {
const expectedSession = {
name: "test",
email: "[email protected]",
picture: "https://test.com/test.png",
}
const expectedSessionInBody = {
name: "test",
email: "[email protected]",
image: "https://test.com/test.png",
}
const encoded = await encode({
salt: SESSION_COOKIE_NAME,
secret: AUTH_SECRET,
token: expectedSession,
})
const request = new Request(SESSION_ACTION, {
headers: {
cookie: `${SESSION_COOKIE_NAME}=${encoded}`,
},
})
const authEvents: AuthConfig['events'] = {
session(message) {
console.log("session event: ", message)
}
}
vi.spyOn(authEvents, "session").mockImplementation((message) => {
console.log("session event: ", message)
})
authConfig.events = authEvents
const authCallbacks: AuthConfig['callbacks'] = {
jwt: async ({ token }) => {
return token
},
session: async ({ session, token }) => {
return session
}
}
vi.spyOn(authCallbacks, "jwt").mockImplementation(async ({ token }) => {
console.log("jwt callback: ", { token })
return token
})
vi.spyOn(authCallbacks, "session").mockImplementation(async ({ session, token }) => {
console.log("session callback: ", { session, token })
return session
})
authConfig.callbacks = authCallbacks
const response = (await Auth(request, authConfig)) as Response
const bodySession = await response.json()

let cookies = {} as Record<string, string>
for (const [name, value] of response.headers.entries()) {
if (name === "set-cookie") {
const cookie = parse(value)
cookies = { ...cookies, ...cookie }
}
}
ThangHuuVu marked this conversation as resolved.
Show resolved Hide resolved
const sessionToken = cookies[SESSION_COOKIE_NAME]
const decoded = await decode<{
// TODO: This shouldn't be necessary?
exp: number
iat: number
jti: string
}>({
salt: SESSION_COOKIE_NAME,
secret: AUTH_SECRET,
token: sessionToken,
})

const { exp, iat, jti, ...actualSession } = decoded || {}

expect(actualSession).toEqual(expectedSession)
expect(bodySession.user).toEqual(expectedSessionInBody)
expect(bodySession.expires).toBeDefined()
expect(authConfig.events?.session).toHaveBeenCalledOnce()
expect(authConfig.callbacks?.jwt).toHaveBeenCalledOnce()
expect(authConfig.callbacks?.session).toHaveBeenCalledOnce()
})
it("should return null if no JWT session in the requests cookies", async () => {
const request = new Request(SESSION_ACTION)
const response = (await Auth(request, authConfig)) as Response
const actual = await response.json()
expect(actual).toEqual(null)
})
})
21 changes: 21 additions & 0 deletions packages/core/src/test-setup.ts
ThangHuuVu marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { afterAll, afterEach, beforeAll } from "vitest"
// import { setupServer } from "msw/node"
// import { handlers } from "./test/handlers"

// const server = setupServer()

// Start server before all tests
beforeAll(() => {
globalThis.crypto ??= require("node:crypto").webcrypto
// return server.listen({ onUnhandledRequest: "error" })
})

// Close server after all tests
afterAll(() => {
// return server.close()
})

// Reset handlers after each test `important for test isolation`
afterEach(() => {
// return server.resetHandlers()
})
9 changes: 9 additions & 0 deletions packages/core/src/test/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const BASE_URL = "https://next-auth-example.com"
export const AUTH_URL = `${BASE_URL}/api/auth`
export const AUTH_SECRET = "secret"

const makeAuthAction = (action: string) => `${AUTH_URL}/${action}`

export const SESSION_ACTION = makeAuthAction("session")
export const SESSION_COOKIE_NAME = "__Secure-authjs.session-token"
export const CSRF_COOKIE_NAME = "__Host-authjs.csrf-token"
1 change: 1 addition & 0 deletions packages/core/src/test/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// import { HttpResponse, http } from "msw"
11 changes: 11 additions & 0 deletions packages/core/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/// <reference types="vitest" />

import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [],
test: {
setupFiles: ['./src/test-setup.ts'],
},
})
Loading
Loading