feat: usage of ESM modules imports (instead of CommonJS) (#5)

Replace `jest` with `tap`.
This commit is contained in:
Divlo
2022-03-20 11:49:27 +01:00
committed by GitHub
parent 91a0e2a76f
commit 19b6f96ecf
70 changed files with 8017 additions and 6318 deletions

View File

@ -1,5 +1,4 @@
import { URL, pathToFileURL } from 'node:url'
import path from 'node:path'
import { URL } from 'node:url'
import dotenv from 'dotenv'
@ -14,16 +13,14 @@ export const JWT_REFRESH_SECRET =
export const JWT_ACCESS_EXPIRES_IN =
process.env.JWT_ACCESS_EXPIRES_IN ?? '15 minutes'
const importMetaURL = pathToFileURL(path.join(__dirname, 'app.js'))
export const SRC_URL = new URL('../../', importMetaURL)
export const SRC_URL = new URL('../../', import.meta.url)
export const ROOT_URL = new URL('../', SRC_URL)
export const EMAIL_URL = new URL('./email/', ROOT_URL)
export const EMAIL_TEMPLATE_URL = new URL('./email-template.ejs', EMAIL_URL)
export const EMAIL_LOCALES_URL = new URL('./locales/', EMAIL_URL)
export const UPLOADS_URL = new URL('./uploads/', ROOT_URL)
export const supportedImageMimetype = [
export const SUPPORTED_IMAGE_MIMETYPE = [
'image/png',
'image/jpg',
'image/jpeg',
@ -31,5 +28,7 @@ export const supportedImageMimetype = [
]
/** in megabytes */
export const maximumImageSize = 10
export const maximumFileSize = 100
export const MAXIMUM_IMAGE_SIZE = 10
/** in megabytes */
export const MAXIMUM_FILE_SIZE = 100

View File

@ -1,10 +1,10 @@
import dotenv from 'dotenv'
import readPackageJSON from 'read-pkg'
import { readPackage } from 'read-pkg'
import { FastifyDynamicSwaggerOptions } from 'fastify-swagger'
dotenv.config()
const packageJSON = readPackageJSON.sync()
const packageJSON = await readPackage()
export const swaggerOptions: FastifyDynamicSwaggerOptions = {
routePrefix: '/documentation',

View File

@ -1,4 +1,4 @@
import * as Prisma from '@prisma/client'
import Prisma from '@prisma/client'
const { PrismaClient } = Prisma

View File

@ -1,77 +1,98 @@
import tap from 'tap'
import sinon from 'sinon'
import httpErrors from 'http-errors'
import jwt from 'jsonwebtoken'
import { userExample } from '../../../models/User.js'
import { prismaMock } from '../../../__test__/setup.js'
import { getUserWithBearerToken } from '../authenticateUser.js'
import prisma from '../../database/prisma.js'
import { userExample } from '../../../models/User.js'
const { Unauthorized, Forbidden, BadRequest } = httpErrors
describe('tools/plugins/authenticateUser - getUserWithBearerToken', () => {
afterEach(() => {
jest.clearAllMocks()
})
it('shoulds succeeds with the right information', async () => {
prismaMock.user.findUnique.mockResolvedValue(userExample)
const currentStrategy = 'local'
jwt.verify = jest.fn<any, any[]>((() => {
return { id: userExample.id, currentStrategy }
}) as any)
const userWithBearerToken = await getUserWithBearerToken('Bearer token')
expect(userWithBearerToken.current.id).toEqual(userExample.id)
expect(userWithBearerToken.current.name).toEqual(userExample.name)
expect(userWithBearerToken.accessToken).toEqual('token')
expect(userWithBearerToken.currentStrategy).toEqual(currentStrategy)
})
it('shoulds throws `Unauthorized` if `bearerToken` is not a string', async () => {
await expect(
async () => await getUserWithBearerToken(undefined)
).rejects.toThrow(Unauthorized)
})
it('shoulds throws `Unauthorized` if `bearerToken` is not to the right format: `"Bearer token"`', async () => {
await expect(
async () => await getUserWithBearerToken('Bearer')
).rejects.toThrow(Unauthorized)
await expect(async () => await getUserWithBearerToken('')).rejects.toThrow(
Unauthorized
)
await expect(
async () => await getUserWithBearerToken('Bearer token token2')
).rejects.toThrow(Unauthorized)
})
it('shoulds throws `Forbidden` if invalid `bearerToken` by `jwt.verify`', async () => {
jwt.verify = jest.fn<any, any[]>((() => {
throw new Error('Invalid token')
}) as any)
await expect(
async () => await getUserWithBearerToken('Bearer token')
).rejects.toThrow(Forbidden)
})
it("shoulds throws `Forbidden` if the user doesn't exist", async () => {
prismaMock.user.findUnique.mockResolvedValue(null)
jwt.verify = jest.fn<any, any[]>((() => {
return { id: userExample.id }
}) as any)
await expect(
async () => await getUserWithBearerToken('Bearer token')
).rejects.toThrow(Forbidden)
})
it('shoulds throws `BadRequest` if the user account is not confirmed', async () => {
prismaMock.user.findUnique.mockResolvedValue({
...userExample,
isConfirmed: false
await tap.test(
'tools/plugins/authenticateUser - getUserWithBearerToken',
async (t) => {
t.afterEach(() => {
sinon.restore()
})
jwt.verify = jest.fn<any, any[]>((() => {
return { id: userExample.id, currentStrategy: 'local' }
}) as any)
await expect(
async () => await getUserWithBearerToken('Bearer token')
).rejects.toThrow(BadRequest)
})
})
await t.test('shoulds succeeds with the right information', async (t) => {
sinon.stub(prisma, 'user').value({
findUnique: async () => {
return userExample
}
})
const currentStrategy = 'local'
sinon.stub(jwt, 'verify').value(() => {
return { id: userExample.id, currentStrategy }
})
const userWithBearerToken = await getUserWithBearerToken('Bearer token')
t.equal(userWithBearerToken.current.id, userExample.id)
t.equal(userWithBearerToken.current.name, userExample.name)
t.equal(userWithBearerToken.accessToken, 'token')
t.equal(userWithBearerToken.currentStrategy, currentStrategy)
})
await t.test(
'shoulds throws `Unauthorized` if `bearerToken` is not a string',
async (t) => {
await t.rejects(getUserWithBearerToken(undefined), Unauthorized)
}
)
await t.test(
'shoulds throws `Unauthorized` if `bearerToken` is not to the right format: `"Bearer token"`',
async (t) => {
await t.rejects(getUserWithBearerToken('Bearer'), Unauthorized)
await t.rejects(getUserWithBearerToken(''), Unauthorized)
await t.rejects(
getUserWithBearerToken('Bearer token token2'),
Unauthorized
)
}
)
await t.test(
'shoulds throws `Forbidden` if invalid `bearerToken` by `jwt.verify`',
async (t) => {
sinon.stub(jwt, 'verify').value(() => {
throw new Error('Invalid token')
})
await t.rejects(getUserWithBearerToken('Bearer token'), Forbidden)
}
)
await t.test(
"shoulds throws `Forbidden` if the user doesn't exist",
async (t) => {
sinon.stub(prisma, 'user').value({
findUnique: async () => {
return null
}
})
sinon.stub(jwt, 'verify').value(() => {
return { id: userExample.id }
})
await t.rejects(getUserWithBearerToken('Bearer token'), Forbidden)
}
)
await t.test(
'shoulds throws `BadRequest` if the user account is not confirmed',
async (t) => {
sinon.stub(prisma, 'user').value({
findUnique: async () => {
return {
...userExample,
isConfirmed: false
}
}
})
sinon.stub(jwt, 'verify').value(() => {
return { id: userExample.id, currentStrategy: 'local' }
})
await t.rejects(getUserWithBearerToken('Bearer token'), BadRequest)
}
)
}
)

View File

@ -1,14 +1,15 @@
import tap from 'tap'
import fastify from 'fastify'
import fastifySocketIo from '../socket-io.js'
describe('tools/plugins/socket-io', () => {
it('should close socket server on fastify close', async () => {
await tap.test('tools/plugins/socket-io', async (t) => {
await t.test('should close socket server on fastify close', async (t) => {
const PORT = 3030
const application = fastify()
await application.register(fastifySocketIo)
await application.listen(PORT)
expect(application.io).not.toBeNull()
t.not(application.io, null)
await application.close()
})
})

View File

@ -1,137 +1,216 @@
import tap from 'tap'
import sinon from 'sinon'
import { userExample } from '../../../models/User.js'
import { userSettingsExample } from '../../../models/UserSettings.js'
import { prismaMock } from '../../../__test__/setup.js'
import { OAuthStrategy } from '../OAuthStrategy.js'
import prisma from '../../database/prisma.js'
import { refreshTokenExample } from '../../../models/RefreshToken.js'
const oauthStrategy = new OAuthStrategy('discord')
describe('/tools/utils/OAuthStrategy - callbackSignin', () => {
it('should signup the user', async () => {
const name = 'Martin'
const id = '12345'
prismaMock.oAuth.findFirst.mockResolvedValue(null)
prismaMock.user.count.mockResolvedValue(0)
prismaMock.user.create.mockResolvedValue({
...userExample,
name
await tap.test('tools/utils/OAuthStrategy', async (t) => {
await t.test('callbackSignin', async (t) => {
t.afterEach(() => {
sinon.restore()
})
prismaMock.userSetting.create.mockResolvedValue(userSettingsExample)
prismaMock.oAuth.create.mockResolvedValue({
id: 1,
userId: userExample.id,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
await t.test('should signup the user', async (t) => {
const name = 'Martin'
const id = '12345'
sinon.stub(prisma, 'user').value({
count: async () => {
return 0
},
create: async () => {
return {
...userExample,
name
}
}
})
sinon.stub(prisma, 'refreshToken').value({
create: async () => {
return refreshTokenExample
}
})
sinon.stub(prisma, 'userSetting').value({
create: async () => {
return userSettingsExample
}
})
sinon.stub(prisma, 'oAuth').value({
findFirst: async () => {
return null
},
create: async () => {
return {
id: 1,
userId: userExample.id,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
}
}
})
const oAuthCreateSpy = sinon.spy(prisma.oAuth, 'create')
const oAuthFindFirstSpy = sinon.spy(prisma.oAuth, 'findFirst')
const userCountSpy = sinon.spy(prisma.user, 'count')
const userCreateSpy = sinon.spy(prisma.user, 'create')
const userSettingCreateSpy = sinon.spy(prisma.userSetting, 'create')
await oauthStrategy.callbackSignin({ id, name })
t.equal(
oAuthCreateSpy.calledWith({
data: {
userId: userExample.id,
provider: 'discord',
providerId: id
}
}),
true
)
t.equal(
oAuthFindFirstSpy.calledWith({
where: {
provider: 'discord',
providerId: id
}
}),
true
)
t.equal(userCountSpy.calledWith({ where: { name } }), true)
t.equal(userCreateSpy.calledWith({ data: { name } }), true)
t.equal(
userSettingCreateSpy.calledWith({
data: {
userId: userExample.id
}
}),
true
)
})
await oauthStrategy.callbackSignin({ id, name })
expect(prismaMock.oAuth.findFirst).toHaveBeenCalledWith({
where: {
provider: 'discord',
providerId: id
})
await t.test('callbackAddStrategy', async (t) => {
t.afterEach(() => {
sinon.restore()
})
await t.test('should add the strategy to the user', async (t) => {
const name = userExample.name
const id = '12345'
sinon.stub(prisma, 'oAuth').value({
findFirst: async () => {
return null
},
create: async () => {
return {
id: 1,
userId: userExample.id,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
}
}
})
const oAuthCreateSpy = sinon.spy(prisma.oAuth, 'create')
const oAuthFindFirstSpy = sinon.spy(prisma.oAuth, 'findFirst')
const result = await oauthStrategy.callbackAddStrategy(
{ id, name },
{ accessToken: '123', current: userExample, currentStrategy: 'local' }
)
t.equal(result, 'success')
t.equal(
oAuthCreateSpy.calledWith({
data: {
userId: userExample.id,
provider: 'discord',
providerId: id
}
}),
true
)
t.equal(
oAuthFindFirstSpy.calledWith({
where: {
provider: 'discord',
providerId: id
}
}),
true
)
})
await t.test(
'should not add the strategy if the account of the provider is already used',
async (t) => {
const name = userExample.name
const id = '12345'
sinon.stub(prisma, 'oAuth').value({
findFirst: async () => {
return {
id: 1,
userId: 2,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
}
}
})
const oAuthFindFirstSpy = sinon.spy(prisma.oAuth, 'findFirst')
const result = await oauthStrategy.callbackAddStrategy(
{ id, name },
{ accessToken: '123', current: userExample, currentStrategy: 'local' }
)
t.equal(result, 'This account is already used by someone else')
t.equal(
oAuthFindFirstSpy.calledWith({
where: {
provider: 'discord',
providerId: id
}
}),
true
)
}
})
expect(prismaMock.user.count).toHaveBeenCalledWith({
where: { name }
})
expect(prismaMock.user.create).toHaveBeenCalledWith({
data: { name }
})
expect(prismaMock.userSetting.create).toHaveBeenCalledWith({
data: {
userId: userExample.id
)
await t.test(
'should not add the strategy if the user is already connected with it',
async (t) => {
const name = userExample.name
const id = '12345'
sinon.stub(prisma, 'oAuth').value({
findFirst: async () => {
return {
id: 1,
userId: userExample.id,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
}
}
})
const oAuthFindFirstSpy = sinon.spy(prisma.oAuth, 'findFirst')
const result = await oauthStrategy.callbackAddStrategy(
{ id, name },
{ accessToken: '123', current: userExample, currentStrategy: 'local' }
)
t.equal(result, 'You are already using this account')
t.equal(
oAuthFindFirstSpy.calledWith({
where: {
provider: 'discord',
providerId: id
}
}),
true
)
}
})
expect(prismaMock.oAuth.create).toHaveBeenCalledWith({
data: {
userId: userExample.id,
provider: 'discord',
providerId: id
}
})
})
})
describe('/tools/utils/OAuthStrategy - callbackAddStrategy', () => {
it('should add the strategy to the user', async () => {
const name = userExample.name
const id = '12345'
prismaMock.oAuth.findFirst.mockResolvedValue(null)
prismaMock.oAuth.create.mockResolvedValue({
id: 1,
userId: userExample.id,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
})
const result = await oauthStrategy.callbackAddStrategy(
{ id, name },
{ accessToken: '123', current: userExample, currentStrategy: 'local' }
)
expect(prismaMock.oAuth.findFirst).toHaveBeenCalledWith({
where: {
provider: 'discord',
providerId: id
}
})
expect(prismaMock.oAuth.create).toHaveBeenCalledWith({
data: {
userId: userExample.id,
provider: 'discord',
providerId: id
}
})
expect(result).toEqual('success')
})
it('should not add the strategy if the account of the provider is already used', async () => {
const name = userExample.name
const id = '12345'
prismaMock.oAuth.findFirst.mockResolvedValue({
id: 1,
userId: 2,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
})
const result = await oauthStrategy.callbackAddStrategy(
{ id, name },
{ accessToken: '123', current: userExample, currentStrategy: 'local' }
)
expect(prismaMock.oAuth.findFirst).toHaveBeenCalledWith({
where: {
provider: 'discord',
providerId: id
}
})
expect(prismaMock.oAuth.create).not.toHaveBeenCalled()
expect(result).toEqual('This account is already used by someone else')
})
it('should not add the strategy if the user is already connected with it', async () => {
const name = userExample.name
const id = '12345'
prismaMock.oAuth.findFirst.mockResolvedValue({
id: 1,
userId: userExample.id,
provider: 'discord',
providerId: id,
updatedAt: new Date(),
createdAt: new Date()
})
const result = await oauthStrategy.callbackAddStrategy(
{ id, name },
{ accessToken: '123', current: userExample, currentStrategy: 'local' }
)
expect(prismaMock.oAuth.findFirst).toHaveBeenCalledWith({
where: {
provider: 'discord',
providerId: id
}
})
expect(prismaMock.oAuth.create).not.toHaveBeenCalled()
expect(result).toEqual('You are already using this account')
)
})
})

View File

@ -1,20 +1,25 @@
import tap from 'tap'
import { buildQueryURL } from '../buildQueryURL.js'
test('/tools/utils/buildQueryUrl', () => {
expect(
await tap.test('tools/utils/buildQueryUrl', async (t) => {
t.equal(
buildQueryURL('http://localhost:8080', {
test: 'query'
})
).toEqual('http://localhost:8080/?test=query')
expect(
}),
'http://localhost:8080/?test=query'
)
t.equal(
buildQueryURL('http://localhost:8080/', {
test: 'query'
})
).toEqual('http://localhost:8080/?test=query')
expect(
}),
'http://localhost:8080/?test=query'
)
t.equal(
buildQueryURL('http://localhost:3000', {
test: 'query',
code: 'abc'
})
).toEqual('http://localhost:3000/?test=query&code=abc')
}),
'http://localhost:3000/?test=query&code=abc'
)
})

View File

@ -1,22 +1,27 @@
import tap from 'tap'
import { parseStringNullish } from '../parseStringNullish.js'
const defaultString = 'defaultString'
describe('/tools/utils/parseStringNullish', () => {
it('returns `defaultString` if `string === undefined`', () => {
expect(parseStringNullish(defaultString, undefined)).toEqual(defaultString)
await tap.test('tools/utils/parseStringNullish', async (t) => {
await t.test(
'returns `defaultString` if `string === undefined`',
async (t) => {
t.equal(parseStringNullish(defaultString, undefined), defaultString)
}
)
await t.test('returns `null` if `string === null`', async (t) => {
t.equal(parseStringNullish(defaultString, null), null)
})
it('returns `null` if `string === null`', () => {
expect(parseStringNullish(defaultString, null)).toEqual(null)
await t.test('returns `null` if `string.length === 0`', async (t) => {
t.equal(parseStringNullish(defaultString, ''), null)
})
it('returns `null` if `string.length === 0`', () => {
expect(parseStringNullish(defaultString, '')).toEqual(null)
})
it('returns `string` if `string.length > 0`', () => {
await t.test('returns `string` if `string.length > 0`', async (t) => {
const string = 'myString'
expect(parseStringNullish(defaultString, string)).toEqual(string)
t.equal(parseStringNullish(defaultString, string), string)
})
})