Learn by Directing AI
All materials

quality-checks.test.ts

tsquality-checks.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest'

vi.mock('../src/lib/db', () => ({
  prisma: {
    qualityCheck: {
      findMany: vi.fn(),
      create: vi.fn(),
    },
  },
}))

import { prisma } from '../src/lib/db'

describe('Quality Checks API', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('should return quality checks for a batch', async () => {
    const mockChecks = [
      { id: 1, batch_id: 1, check_type: 'moisture', result: 'pass', moisture_pct: 6.2 },
      { id: 2, batch_id: 1, check_type: 'defect_rate', result: 'pass', defect_pct: 1.8 },
    ]
    ;(prisma.qualityCheck.findMany as ReturnType<typeof vi.fn>).mockResolvedValue(mockChecks)

    const result = await prisma.qualityCheck.findMany({
      where: { batch_id: 1 },
      include: { batch: { select: { variete: true, stage: true } } },
      orderBy: { checked_at: 'desc' },
    })

    expect(result).toHaveLength(2)
    expect(result[0].result).toBe('pass')
  })

  it('should create a quality check', async () => {
    const newCheck = {
      id: 3,
      batch_id: 1,
      check_type: 'moisture',
      result: 'fail',
      moisture_pct: 12.5,
      inspector: 'Konan Y.',
    }
    ;(prisma.qualityCheck.create as ReturnType<typeof vi.fn>).mockResolvedValue(newCheck)

    const result = await prisma.qualityCheck.create({
      data: {
        batch_id: 1,
        check_type: 'moisture',
        result: 'fail',
        moisture_pct: 12.5,
        inspector: 'Konan Y.',
      },
    })

    expect(result.result).toBe('fail')
    expect(result.moisture_pct).toBe(12.5)
  })
})