Last active
April 2, 2024 19:42
-
-
Save mr-feek/0efb2e9af74ac1d1b53cc2f08f11579d to your computer and use it in GitHub Desktop.
japa assert.seeInDatabase plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PluginFn } from '@japa/runner'; | |
import { Assert } from '@japa/assert'; | |
import Database from '@ioc:Adonis/Lucid/Database'; | |
declare module '@japa/assert' { | |
interface Assert { | |
seeInDatabase(tableName: string, data: {}, count?: number): Promise<void>; | |
notInDatabase(tableName: string, data: {}): Promise<void>; | |
seeSoftDeletedInDatabase(tableName: string, data: {}, count?: number): Promise<void>; | |
} | |
} | |
export function seeInDatabase(): PluginFn { | |
return function (_, __, {}) { | |
Assert.macro('seeInDatabase', async function (tableName: string, data: {}, count: number = 1) { | |
const inDatabase = await Database.from(tableName).where(data).select('*'); | |
this.lengthOf(inDatabase, count, await buildErrorMessage(tableName, data, count)); | |
}); | |
Assert.macro('notInDatabase', async function (tableName: string, data: {}) { | |
await this.seeInDatabase(tableName, data, 0); | |
}); | |
Assert.macro('seeSoftDeletedInDatabase', async function (tableName: string, data: {}, count?: number) { | |
// assert that the data is there without scoping to deleted_at | |
await this.seeInDatabase(tableName, data, count); | |
// now assert that it isn't there if we add a null deleted_at | |
await this.notInDatabase(tableName, { | |
...data, | |
deleted_at: null, | |
}); | |
}); | |
}; | |
} | |
async function buildErrorMessage(tableName: string, data: { id?: string }, count: number): Promise<string> { | |
const expectedStringified = JSON.stringify(data, null, ' '); | |
let error = `failed to find:\n\n${expectedStringified}\n\nrecord inside of the '${tableName}' table.\n`; | |
if (count === 0) { | |
error = `we found a record inside the ${tableName} table that we didnt want to find\n`; | |
} | |
let foundStringified = await tryFindingSimilar(tableName, data); | |
if (foundStringified) { | |
error += ` We found:\n\n${foundStringified}\n\n`; | |
} | |
return error; | |
} | |
async function tryFindingSimilar(tableName: string, data: { id?: string }) { | |
// find all columns that have an id | |
const keysToTry = Object.keys(data).filter(key => { | |
return /id$/.test(key); | |
}); | |
for (const key of keysToTry) { | |
const foundById = await Database.from(tableName).where(key, data[key]).select('*'); | |
if (foundById.length) { | |
return JSON.stringify(foundById[0], null, ' '); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment