Testing guide / Environment
A test environment
createTestEnv builds a migrated database from your schema, mounts your Junction app over it, and hands back the tools to arrange rows, call as a user and see what was announced. @frontierjs/testing sits above Junction, so it can do what Litestone's own createTestEnv cannot: run the app.
model Lead {
id Int
name String
(2.4.4.5)
}
import { createTestEnv, sessionContext } from '@frontierjs/testing'
import { createApp, createService } from '@frontierjs/junction'
import { GatePlugin } from '@frontierjs/litestone'
const gate = new GatePlugin({ getLevel: (user) => (user ? 4 : 0) })
const env = await createTestEnv({
schema: './schema.lite',
plugins: [gate],
api: ({ db }) => {
const app = createApp({ db })
app.services.register(createService({ name: 'leads', model: 'Lead' }))
return app
},
})
const user = sessionContext({ id: 'u1', role: 'member' })
const t = env.phases({ as: user })
await t.act(() => env.as(user).service('leads').create({ name: 'Ada' }))
await t.assert(async (read) => {
if (await read.lead.count() !== 1) throw new Error('expected one lead')
})
if (env.announced('leads:created').length !== 1) throw new Error('expected one announcement')
await env.close()
The app is built over the env's own client, never a second one on the same file, so what a factory writes and what a service reads are the same rows. env.as(user).service('leads') puts the user through the whole request path except the socket.
What else it can do
api:takes an app or a function of{ db, system, factories, schema, path, dir }; without it you get Litestone's env unchangedmigrations:builds the database from your committed migration files instead of the schemaenv.phases({ as })givesarrange,actandassert;arrangewrites below the boundary, so it announces nothingenv.announced(event?)answers what the current act announced, andenv.clearAnnounced()is for a test not usingphases()env.httpis Junction'srequest(app), and auth is the app's to issuelisten: truebinds a real port, asked for as 0, and setsenv.urlandenv.portenv.close()is async, because it stops the app's plugins first- An app built with
createApp({ root })reads itsjunction.config.jsunder test asstart()does - An
app.tsthat opens the database at import cannot be mounted this way; exportbuildApp({ db })as the scaffold does
In depth: testing README, Testing § createTestEnv