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

feat: add unit tests #25

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ node_modules
src/data/announcements.json
src/data/cl-events.json
database/
docs/out/
docs/out/
coverage/
68 changes: 68 additions & 0 deletions __tests__/auth-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { GraphQLError } from 'graphql'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'

import {
adminRole,
checkAuthorization,
sportRole,
} from '../src/utils/auth-utils'

describe('auth-utils', () => {
beforeEach(() => {
process.env.NODE_ENV = 'test'
process.env.BYPASS_AUTH_IN_DEV = 'false'
})

afterEach(() => {
delete process.env.NODE_ENV
delete process.env.BYPASS_AUTH_IN_DEV
})

describe('checkAuthorization', () => {
it('should not throw an error when the user has the required role', () => {
const contextValue = {
jwtPayload: { groups: [sportRole, adminRole] },
}

expect(() =>
checkAuthorization(contextValue, sportRole)
).not.toThrow()
})

it('should throw an error when the user does not have the required role', () => {
const contextValue = { jwtPayload: { groups: [adminRole] } }

expect(() => checkAuthorization(contextValue, sportRole)).toThrow(
GraphQLError
)
})

it('should throw an error when jwtPayload is missing', () => {
const contextValue = {}

expect(() => checkAuthorization(contextValue, sportRole)).toThrow(
GraphQLError
)
})

it('should not throw an error when NODE_ENV is not production and BYPASS_AUTH_IN_DEV is true', () => {
process.env.NODE_ENV = 'development'
process.env.BYPASS_AUTH_IN_DEV = 'true'
const contextValue = { jwtPayload: { groups: [] } }

expect(() =>
checkAuthorization(contextValue, sportRole)
).not.toThrow()
})

it('should throw an error when NODE_ENV is production and BYPASS_AUTH_IN_DEV is true', () => {
process.env.NODE_ENV = 'production'
process.env.BYPASS_AUTH_IN_DEV = 'true'
const contextValue = { jwtPayload: { groups: [] } }

expect(() => checkAuthorization(contextValue, sportRole)).toThrow(
GraphQLError
)
})
})
})
69 changes: 69 additions & 0 deletions __tests__/date-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { describe, expect, it } from 'vitest'

import {
addWeek,
formatISODate,
getDays,
getMonday,
getWeek,
isoToPostgres,
} from '../src/utils/date-utils'

describe('date-utils', () => {
describe('formatISODate', () => {
it('should format a date to ISO string', () => {
const date = new Date('2020-10-01')
expect(formatISODate(date)).toBe('2020-10-01')
})

it('should return an empty string for undefined date', () => {
expect(formatISODate(undefined)).toBe('')
})
})

describe('getMonday', () => {
it('should return the start of the week for a given date', () => {
const date = new Date('2024-11-22') // Friday
const monday = getMonday(date)
expect(monday.toISOString().split('T')[0]).toBe('2024-11-18')
})
})

describe('getWeek', () => {
it('should return the start and end of the week for a given date', () => {
const date = new Date('2020-10-07') // Wednesday
const [start, end] = getWeek(date)
expect(start.toISOString().split('T')[0]).toBe('2020-10-05')
expect(end.toISOString().split('T')[0]).toBe('2020-10-12')
})
})

describe('getDays', () => {
it('should return all days between two dates', () => {
const begin = new Date('2020-10-01')
const end = new Date('2020-10-05')
const days = getDays(begin, end)
expect(days.map((d) => d.toISOString().split('T')[0])).toEqual([
'2020-10-01',
'2020-10-02',
'2020-10-03',
'2020-10-04',
])
})
})

describe('addWeek', () => {
it('should add weeks to a date', () => {
const date = new Date('2020-10-01')
const newDate = addWeek(date, 2)
expect(newDate.toISOString().split('T')[0]).toBe('2020-10-15')
})
})

describe('isoToPostgres', () => {
it('should convert ISO date string to Postgres date string', () => {
const isoDate = new Date('2020-10-01T00:00:00Z').getTime()
expect(isoToPostgres(isoDate)).toBe('2020-10-01 00:00:00.000')
})
})
})
167 changes: 167 additions & 0 deletions __tests__/food-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { describe, expect, it } from 'vitest'

import {
capitalize,
cleanMealFlags,
getMealDayHash,
getMealHash,
isEmpty,
mergeMealVariants,
parseGermanFloat,
parseXmlFloat,
unifyFoodEntries,
} from '../src/utils/food-utils'

describe('cleanMealFlags', () => {
it('should remove contradictory flags', () => {
const flags = ['veg', 'R']
expect(cleanMealFlags(flags)).toEqual(['R'])
})
it('should return null if flags are null', () => {
expect(cleanMealFlags(null)).toBeNull()
})
})

describe('capitalize', () => {
it('should capitalize the first letter of meal names', () => {
const mealNames = { de: 'veganer burger', en: 'vegan burger' }
expect(capitalize(mealNames)).toEqual({
de: 'Veganer burger',
en: 'Vegan burger',
})
})
it('should throw an error if mealNames do not have both de and en properties', () => {
const mealNames = { de: 'veganer burger' }
// @ts-expect-error - Testing for error
expect(() => capitalize(mealNames)).toThrow(
'mealNames must have both de and en properties'
)
})
})

describe('unifyFoodEntries', () => {
it('should unify food entries', () => {
const entries = [
{
timestamp: '12-12-2020',
meals: [
{
name: { de: 'burger', en: 'burger' },
category: 'main',
prices: { student: 1.5, employee: 2.5, guest: 3.5 },
allergens: null,
flags: ['veg'],
nutrition: null,
originalLanguage: 'de',
static: false,
restaurant: 'test',
additional: false,
mealId: 'test-id',
id: '1',
parent: null,
},
],
},
]
expect(unifyFoodEntries(entries)).toEqual([
{
timestamp: '12-12-2020',
meals: [
{
name: { de: 'Burger', en: 'Burger' },
category: 'main',
prices: { student: 1.5, employee: 2.5, guest: 3.5 },
allergens: null,
flags: ['veg'],
nutrition: null,
originalLanguage: 'de',
static: false,
restaurant: 'test',
additional: false,
mealId: expect.any(String),
id: '1',
parent: null,
variants: null,
},
],
},
])
})
})

describe('mergeMealVariants', () => {
it('should merge meal variants', () => {
const entries = [
{
timestamp: '12-12-2020',
meals: [
{
name: 'name',
category: 'main',
prices: { student: 1.5, employee: 2.5, guest: 3.5 },
allergens: null,
flags: ['veg'],
nutrition: null,
originalLanguage: 'de',
static: false,
restaurant: 'test',
additional: false,
mealId: 'test-id',
id: '1',
parent: null,
},
],
},
]
expect(mergeMealVariants(entries)).toEqual(entries)
})
})

describe('getMealDayHash', () => {
it('should generate a pseudo-unique hash', () => {
const day = '2023-10-01'
const mealName = 'burger'
expect(getMealDayHash(day, mealName)).toMatch(/^\d{2}[a-z0-9]{6}$/)
})
})

describe('getMealHash', () => {
it('should generate a unique hash', () => {
const mealName = 'burger'
const category = 'main'
const restaurant = 'test'
expect(getMealHash(mealName, category, restaurant)).toMatch(
/^[a-z0-9]+$/
)
})
})

describe('parseGermanFloat', () => {
it('should parse a German float', () => {
expect(parseGermanFloat('1,5')).toBe(1.5)
})
it('should return null for undefined input', () => {
expect(parseGermanFloat(undefined)).toBeNull()
})
})

describe('parseXmlFloat', () => {
it('should parse an XML float', () => {
expect(parseXmlFloat({ _text: '1,5' })).toBe(1.5)
})
it('should return 0 for null input', () => {
expect(parseXmlFloat({ _text: 'null' })).toBe(0)
})
})

describe('isEmpty', () => {
it('should return true for empty values', () => {
expect(isEmpty(null)).toBe(true)
expect(isEmpty('')).toBe(true)
expect(isEmpty(' ')).toBe(true)
})
it('should return false for non-empty values', () => {
expect(isEmpty('test')).toBe(false)
expect(isEmpty(123)).toBe(false)
})
})
Binary file modified bun.lockb
Binary file not shown.
4 changes: 2 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ const apolloServer = new ApolloServer({
typeDefs,
resolvers,
plugins: [
Bun.env.NODE_ENV === 'production'
process.env.NODE_ENV === 'production'
? ApolloServerPluginLandingPageProductionDefault({
footer: false,
})
: ApolloServerPluginLandingPageLocalDefault(),
],
introspection: Bun.env.NODE_ENV !== 'production',
introspection: process.env.NODE_ENV !== 'production',
formatError(formattedError, error) {
console.error(error)
return formattedError
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"@types/pdf-parse": "^1.1.4",
"@types/sanitize-html": "^2.13.0",
"@typescript-eslint/eslint-plugin": "^8.15.0",
"@vitest/coverage-v8": "2.1.5",
"concurrently": "^9.1.0",
"cross-env": "^7.0.3",
"drizzle-kit": "^0.28.1",
Expand All @@ -61,7 +62,9 @@
"lint-staged": "^15.2.10",
"prettier": "^3.3.3",
"typescript": "^5.6.3",
"typescript-eslint": "^8.15.0"
"typescript-eslint": "^8.15.0",
"vite-tsconfig-paths": "^5.1.3",
"vitest": "^2.1.5"
},
"lint-staged": {
"**/*.{js,jsx,ts,tsx,mjs}": [
Expand Down
15 changes: 15 additions & 0 deletions src/db/migrations/0007_jazzy_brood.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS "manual_cl_events" (
"id" serial PRIMARY KEY NOT NULL,
"title_de" text NOT NULL,
"title_en" text NOT NULL,
"description_de" text,
"description_en" text,
"start_date_time" timestamp with time zone NOT NULL,
"end_date_time" timestamp with time zone,
"organizer" text NOT NULL,
"url" text,
"instagram" text,
"event_url" text,
"created_at" timestamp with time zone NOT NULL,
"updated_at" timestamp with time zone NOT NULL
);
Loading