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

A vitest example #437

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: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ yarn-error.log*
lerna-debug.log*
.DS_Store

# test profiling data
profiling

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

Expand Down
39 changes: 8 additions & 31 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,39 +77,16 @@
"console": "integratedTerminal"
},
{
"name": "Debug Jest Tests",
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"type": "node",
"request": "launch",
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
},
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/node_modules/.bin/jest",
"--runInBand",
"history"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"name": "vscode-jest-tests.v2",
"request": "launch",
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
},
"args": [
"${workspaceRoot}/node_modules/.bin/jest",
"--runInBand",
"--watchAll=false",
"--testNamePattern",
"${jest.testNamePattern}",
"--runTestsByPath",
"${jest.testFile}"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
"name": "Debug Tests",
"autoAttachChildProcesses": true,
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],
"program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
"args": ["run"],
"smartStep": true,
"console": "integratedTerminal"
}
]
}
19 changes: 0 additions & 19 deletions jest.config.cjs

This file was deleted.

8 changes: 2 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,17 @@
"license": "AGPL-3.0-or-later",
"devDependencies": {
"@types/auth0": "^3.3.2",
"@types/jest": "^29.4.0",
"@types/node": "^18.13.0",
"@types/supertest": "^2.0.12",
"@types/underscore": "^1.11.4",
"cross-env": "^7.0.3",
"husky": "^8.0.1",
"jest": "^29.7.0",
"jest-extended": "^4.0.2",
"mongodb-memory-server": "^10.1.2",
"nock": "^13.3.0",
"supertest": "^6.3.3",
"ts-jest": "^29.2.5",
"ts-standard": "^12.0.0",
"typescript": "4.9.5",
"wait-for-expect": "^3.0.2"
"vitest": "^2.1.8"
},
"dependencies": {
"@apollo/server": "^4.11.2",
Expand Down Expand Up @@ -73,7 +69,7 @@
"scripts": {
"lint": "yarn ts-standard",
"fix": "yarn ts-standard --fix",
"test": "cross-env NODE_OPTIONS=\"--experimental-vm-modules\" jest --runInBand",
"test": "vitest run --silent",
"build": "tsc -p tsconfig.json",
"build-release": "tsc -p tsconfig.release.json",
"clean": "tsc -b --clean && rm -rf build/*",
Expand Down
124 changes: 53 additions & 71 deletions src/__tests__/areas.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,35 @@
import { ApolloServer } from '@apollo/server'
import muuid from 'uuid-mongodb'
import { jest } from '@jest/globals'
import MutableAreaDataSource from '../model/MutableAreaDataSource.js'
import MutableOrganizationDataSource from '../model/MutableOrganizationDataSource.js'
import { AreaType } from '../db/AreaTypes.js'
import { OrganizationEditableFieldsType, OrganizationType, OrgType } from '../db/OrganizationTypes.js'
import { queryAPI, setUpServer } from '../utils/testUtils.js'
import { muuidToString } from '../utils/helpers.js'
import { InMemoryDB } from '../utils/inMemoryDB.js'
import express from 'express'
import { gqlTest } from './fixtures/gql.fixtures.js'
interface LocalContext {
includedChild: AreaType
excludedArea: AreaType
alphaFields: OrganizationEditableFieldsType
alphaOrg: OrganizationType
}

jest.setTimeout(60000)

describe('areas API', () => {
let server: ApolloServer
let user: muuid.MUUID
let userUuid: string
let app: express.Application
let inMemoryDB: InMemoryDB

// Mongoose models for mocking pre-existing state.
let areas: MutableAreaDataSource
let organizations: MutableOrganizationDataSource
let usa: AreaType
let ca: AreaType
let wa: AreaType

beforeAll(async () => {
({ server, inMemoryDB, app } = await setUpServer())
// Auth0 serializes uuids in "relaxed" mode, resulting in this hex string format
// "59f1d95a-627d-4b8c-91b9-389c7424cb54" instead of base64 "WfHZWmJ9S4yRuTicdCTLVA==".
user = muuid.mode('relaxed').v4()
userUuid = muuidToString(user)
})

beforeEach(async () => {
await inMemoryDB.clear()
areas = MutableAreaDataSource.getInstance()
organizations = MutableOrganizationDataSource.getInstance()
usa = await areas.addCountry('usa')
ca = await areas.addArea(user, 'CA', usa.metadata.area_id)
wa = await areas.addArea(user, 'WA', usa.metadata.area_id)
})
const it = gqlTest.extend<LocalContext>({
includedChild: async ({ addArea, area }, use) => await use(await addArea(undefined, { parent: area })),
excludedArea: async ({ addArea, area }, use) => await use(await addArea(undefined, { parent: area })),
alphaFields: async ({ excludedArea, task, area }, use) => await use({
displayName: task.id,
associatedAreaIds: [area.metadata.area_id],
excludedAreaIds: [excludedArea.metadata.area_id]
}),
alphaOrg: async ({ organizations, user, alphaFields }, use) => {
const org = await organizations.addOrganization(user, OrgType.localClimbingOrganization, alphaFields)
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})

afterAll(async () => {
await server.stop()
await inMemoryDB.close()
})
await use(org)
await organizations.deleteFromCacheById(org._id)
}
})

describe('areas API', () => {
describe('queries', () => {
const areaQuery = `
query area($input: ID) {
Expand All @@ -59,50 +41,50 @@ describe('areas API', () => {
}
}
`
let alphaFields: OrganizationEditableFieldsType
let alphaOrg: OrganizationType

beforeEach(async () => {
alphaFields = {
displayName: 'USA without CA Org',
associatedAreaIds: [usa.metadata.area_id],
excludedAreaIds: [ca.metadata.area_id]
}
alphaOrg = await organizations.addOrganization(user, OrgType.localClimbingOrganization, alphaFields)
.then((res: OrganizationType | null) => {
if (res === null) throw new Error('Failure mocking organization.')
return res
})
})

it('retrieves an area omitting organizations that exclude it', async () => {
const response = await queryAPI({
it('retrieves an area omitting organizations that exclude it', async ({ query, userUuid, excludedArea }) => {
const response = await query({
query: areaQuery,
operationName: 'area',
variables: { input: ca.metadata.area_id },
userUuid,
app
variables: { input: muuidToString(excludedArea.metadata.area_id) },
userUuid
})

expect(response.statusCode).toBe(200)
const areaResult = response.body.data.area
expect(areaResult.uuid).toBe(muuidToString(ca.metadata.area_id))
expect(areaResult).toBeTruthy()
expect(areaResult.uuid).toBe(muuidToString(excludedArea.metadata.area_id))
// Even though alphaOrg associates with ca's parent, usa, it excludes
// ca and so should not be listed.
expect(areaResult.organizations).toHaveLength(0)
})

it.each([userUuid, undefined])('retrieves an area and lists associated organizations', async (userId) => {
const response = await queryAPI({
it('retrieves an area and lists associated organizations', async ({ query, userUuid, includedChild, alphaOrg }) => {
const response = await query({
query: areaQuery,
operationName: 'area',
variables: { input: muuidToString(includedChild.metadata.area_id) },
userUuid
})

expect(response.statusCode).toBe(200)
const areaResult = response.body.data.area
expect(areaResult.uuid).toBe(muuidToString(includedChild.metadata.area_id))
expect(areaResult.organizations).toHaveLength(1)
expect(areaResult.organizations[0].orgId).toBe(muuidToString(alphaOrg.orgId))
})

it('retrieves an area and lists associated organizations, even with no auth context', async ({ query, includedChild, alphaOrg }) => {
const response = await query({
query: areaQuery,
operationName: 'area',
variables: { input: wa.metadata.area_id },
userUuid: userId,
app
variables: { input: muuidToString(includedChild.metadata.area_id) }
})

expect(response.statusCode).toBe(200)
const areaResult = response.body.data.area
expect(areaResult.uuid).toBe(muuidToString(wa.metadata.area_id))
expect(areaResult.uuid).toBe(muuidToString(includedChild.metadata.area_id))
console.log(areaResult)
expect(areaResult.organizations).toHaveLength(1)
expect(areaResult.organizations[0].orgId).toBe(muuidToString(alphaOrg.orgId))
})
Expand Down
Loading
Loading