You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import{TestClient}from'@atlex/testing'constresponse=awaitTestClient.get('/users')response.assertOk()// 200response.assertCreated()// 201response.assertNoContent()// 204response.assertRedirect()// 3xxresponse.assertBadRequest()// 400response.assertUnauthorized()// 401response.assertForbidden()// 403response.assertNotFound()// 404response.assertStatus(200)// Specific statusresponse.assertStatus(200,201)// One of statuses
Content Assertions
constresponse=awaitTestClient.get('/users')// Get JSON responseconstjson=response.json()constusers=response.json().data// Get text responseconsttext=response.text()// Access headersconstcontentType=response.headers()['content-type']
import{test}from'vitest'import{TestClient,MailFake}from'@atlex/testing'test('sends welcome email',async()=>{constmailFake=newMailFake()awaitTestClient.post('/register',{name: 'John Doe',email: 'john@example.com',})// Assert email was sentmailFake.assertSent('john@example.com',WelcomeEmail)// Assert email countmailFake.assertCount(1)// Get sent mailsconstmails=mailFake.sent()})
Queue Fake
import{QueueFake}from'@atlex/testing'test('dispatches background job',async()=>{constqueueFake=newQueueFake()awaitTestClient.post('/orders',orderData)// Assert job was dispatchedqueueFake.assertDispatched(ProcessOrderJob)// Assert with payloadqueueFake.assertDispatched(ProcessOrderJob,(job)=>{returnjob.orderId===123})// Get dispatched jobsconstjobs=queueFake.dispatched()})
Event Fake
import{EventFake}from'@atlex/testing'test('fires user created event',async()=>{consteventFake=newEventFake()awaitTestClient.post('/users',userData)// Assert event was firedeventFake.assertDispatched(UserCreated)// Assert with payloadeventFake.assertDispatched(UserCreated,(event)=>{returnevent.user.email==='john@example.com'})})
Storage Fake
import{StorageFake}from'@atlex/testing'test('uploads file',async()=>{conststorageFake=newStorageFake()awaitTestClient.post('/upload',formData)// Assert file was storedstorageFake.assertStored('avatars/user.jpg')// Assert missingstorageFake.assertMissing('old/avatar.jpg')// Get stored filesconstfiles=storageFake.stored()})
import{CacheFake}from'@atlex/testing'test('caches user data',async()=>{constcacheFake=newCacheFake()awaitTestClient.get('/users/1')// Assert value was cachedcacheFake.assertHas('user:1')// Get cached valueconstcached=cacheFake.get('user:1')})
Log Fake
import{LogFake}from'@atlex/testing'test('logs errors',async()=>{constlogFake=newLogFake()awaitTestClient.get('/invalid-route')// Assert log entrylogFake.assertLogged('error',(log)=>{returnlog.message.includes('Route not found')})})
import{test}from'vitest'import{seed}from'@atlex/testing'test.beforeEach(async()=>{awaitseed(async(factory)=>{// Create test dataawaitfactory.model(User).create({name: 'Admin',role: 'admin',})awaitfactory.model(Post).times(5).create()})})
Factories: Test Data Generation
Creating Test Data
import{Factory}from'@atlex/testing'// Create single modelconstuser=awaitFactory.make(User)// Create with attributesconstuser=awaitFactory.make(User,{name: 'John Doe',email: 'john@example.com',})// Create and persistconstuser=awaitFactory.create(User)// Create multipleconstusers=awaitFactory.times(5).create(User)// Chain methodsconstusers=awaitFactory.times(3).create(User,{role: 'admin'})
Defining Factories
import{Factory}from'@atlex/testing'classUserFactoryextendsFactory{model(){returnUser}definition(){return{name: this.faker.person.fullName(),email: this.faker.internet.email(),password: 'password',emailVerifiedAt: newDate(),}}}// Use factoryconstuser=awaitUserFactory.create()// With overridesconstadmin=awaitUserFactory.create({role: 'admin'})
Time Helpers
Freezing Time
import{test}from'vitest'import{freezeTime,unfreezeTime,now}from'@atlex/testing'test('handles time-based logic',()=>{freezeTime('2024-03-15 14:30:00')consttimestamp=now()// March 15, 2024 14:30unfreezeTime()})
Traveling Time
import{travelTo,travelForward,travelBack}from'@atlex/testing'test('schedules task',async()=>{constscheduled=newDate('2024-03-15')// Travel to specific timetravelTo('2024-03-15 10:00:00')// Travel forwardtravelForward('1 day')travelForward('2 hours')// Travel backwardtravelBack('30 minutes')})
Complete Example
import{test}from'vitest'import{TestClient,useDatabase,refreshDatabase,Factory,MailFake,freezeTime,unfreezeTime,}from'@atlex/testing'test('user registration flow',async()=>{awaituseDatabase('testing')awaitrefreshDatabase()freezeTime('2024-03-15 10:00:00')constmailFake=newMailFake()// Register userconstresponse=awaitTestClient.post('/register',{name: 'Jane Doe',email: 'jane@example.com',password: 'password123',})// Assert responseresponse.assertCreated()response.assertJson({message: 'Registration successful',})// Assert email sentmailFake.assertSent('jane@example.com',VerifyEmailNotification)// Assert user created in databaseconstuser=awaitUser.where('email','jane@example.com').first()expect(user).toBeDefined()unfreezeTime()})test('can edit user profile',async()=>{constuser=awaitFactory.create(User)constresponse=awaitTestClient.actingAs(user).put(`/users/${user.id}`,{name: 'Jane Doe',bio: 'Test bio',})response.assertOk()constupdated=awaitUser.find(user.id)expect(updated.name).toBe('Jane Doe')})test('requires authentication',async()=>{constresponse=awaitTestClient.get('/dashboard')response.assertUnauthorized()})test('enforces authorization',async()=>{constuser=awaitFactory.create(User,{role: 'user'})constadmin=awaitFactory.create(User,{role: 'admin'})constresponse=awaitTestClient.actingAs(user).delete(`/users/${admin.id}`)response.assertForbidden()})
Custom Matchers
import{expect}from'vitest'import{addCustomMatchers}from'@atlex/testing'addCustomMatchers({toBeValidEmail: (email: string)=>{constvalid=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)return{pass: valid,message: ()=>`Expected ${email} to be a valid email`,}},})test('validates email',()=>{expect('john@example.com').toBeValidEmail()})