64 lines
1.9 KiB
TypeScript
64 lines
1.9 KiB
TypeScript
import {test, expect, beforeAll} from "vitest";
|
|
import {query} from "../src";
|
|
import {Invoice} from "./Invoice";
|
|
import {setupDefaultInvoices} from "./database";
|
|
|
|
beforeAll(async () => {
|
|
await setupDefaultInvoices();
|
|
});
|
|
|
|
test("retrieve existing models from database", async () => {
|
|
const invoice = await query(Invoice).find(1);
|
|
const invoices = await query(Invoice).findMany(1, 2);
|
|
|
|
expect(invoice).not.toBeNull();
|
|
expect(invoices).toHaveLength(2);
|
|
|
|
expect(invoice?.amount).toStrictEqual(5450.12);
|
|
|
|
expect(invoices.reduce((total, invoice) => (total + invoice.amount), 0)).toStrictEqual(5450.12 + 1122.54);
|
|
|
|
expect(invoices[0].date.getFullYear()).toStrictEqual(1997);
|
|
})
|
|
|
|
test("alter existing model in database", async () => {
|
|
// Get an invoice to change its date.
|
|
const invoice = await query(Invoice).find(1) as Invoice;
|
|
invoice.date.setDate(15);
|
|
await invoice.drizzle().save();
|
|
|
|
// Get the same invoice again, to check that the date has been successfully changed.
|
|
const updatedInvoice = await query(Invoice).find(1);
|
|
expect(updatedInvoice?.date?.getDate()).toStrictEqual(15);
|
|
});
|
|
|
|
test("refresh a model from database", async () => {
|
|
// Get an invoice to change its date.
|
|
const invoice = await query(Invoice).find(1) as Invoice;
|
|
invoice.date.setDate(30);
|
|
// Refresh from database: it should revert the changes.
|
|
await invoice.drizzle().refresh();
|
|
|
|
expect(invoice?.date?.getDate()).toStrictEqual(15);
|
|
});
|
|
|
|
test("insert a new model in database", async () => {
|
|
const now = new Date();
|
|
|
|
const invoice = new Invoice();
|
|
invoice.date = now;
|
|
invoice.amount = 12.34;
|
|
invoice.clientName = "client name";
|
|
invoice.clientAddress = "any address string";
|
|
|
|
await invoice.drizzle().save();
|
|
|
|
expect(invoice.serialize()).toStrictEqual({
|
|
id: 3,
|
|
date: now.toISOString(),
|
|
amount: "12.34",
|
|
clientName: "client name",
|
|
clientAddress: "any address string",
|
|
});
|
|
expect(invoice.serialize()).toStrictEqual((await query(Invoice).find(invoice.id))?.serialize());
|
|
});
|