Skip to content

Instantly share code, notes, and snippets.

@lordzouga
Last active November 3, 2022 11:49
Show Gist options
  • Save lordzouga/1d6ffbae82ccd3665af6e375a838df6a to your computer and use it in GitHub Desktop.
Save lordzouga/1d6ffbae82ccd3665af6e375a838df6a to your computer and use it in GitHub Desktop.
A basic unit test example for nuxt3 composable + prisma with vitest
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { setup } from '@nuxt/test-utils-edge';
import { PrismaClient } from '@prisma/client';
// import { useAddJob } from '../composables/getdata.js';
/* this is useAddJob from getdata.js */
const prisma = new PrismaClient();
/* a simple function to be tested */
export async function useAddJob(jobData){
const job = await prisma.job.create({
data: jobData
})
return { job }
}
/* a basic list of jobs based on my prisma Job Schema */
const mockJobs = [
{
id: 56878,
company: "Netloop",
summary: "Some job summary",
title: "job title",
location: "San francisco",
url: "https://ominia.com/be-my-employee",
salaryMax: 30000,
salaryMin: 20000,
timePosted: 134548974
},
{
id: 45590,
company: "Google",
summary: "an awesome job ",
title: "Somer Over",
location: "Ohio",
url: "https://omperseron.com/job-my-bruh",
salaryMax: 50000,
salaryMin: 30000,
timePosted: 1237438445
}
]
/* mock `@prisma/client` module based on https://vitest.dev/guide/mocking.html#modules */
vi.mock('@prisma/client', () => {
const Job = vi.fn();
Job.prototype.create = vi.fn();
Job.prototype.findMany = vi.fn();
Job.prototype.findFirst = vi.fn();
function PrismaClient(){
this.job = new Job()
}
return { PrismaClient }
})
describe('Make sure database operations are working', async () => {
let prisma;
await setup({
server: true
})
beforeEach(() => {
prisma = new PrismaClient();
})
afterEach( () => {
vi.clearAllMocks();
})
it("tests that useAddJob runs correctly", async ()=> {
prisma.job.create.mockResolvedValueOnce(mockJobs[0])
const { job } = await useAddJob(mockJobs[0]);
expect(prisma.job.create).toBeCalledWith({ data: mockJobs[0] })
expect(job.id == mockJobs[0].id).toBeTruthy();
} )
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment