swaf/test/Model.test.ts

67 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-04-23 11:40:55 +02:00
import MysqlConnectionManager from "../src/db/MysqlConnectionManager";
import Model from "../src/db/Model";
import {MIGRATIONS} from "./_migrations";
import ModelFactory from "../src/db/ModelFactory";
2020-04-23 11:40:55 +02:00
class FakeDummyModel extends Model {
public id?: number = undefined;
public name?: string = undefined;
public date?: Date = undefined;
public date_default?: Date = undefined;
2020-04-23 11:40:55 +02:00
protected init(): void {
this.setValidation('name').acceptUndefined().between(3, 256);
2020-04-23 11:40:55 +02:00
}
}
beforeAll(async (done) => {
MysqlConnectionManager.registerMigrations(MIGRATIONS);
ModelFactory.register(FakeDummyModel);
2020-04-23 11:40:55 +02:00
await MysqlConnectionManager.prepare();
done();
});
afterAll(async (done) => {
await MysqlConnectionManager.endPool();
done();
});
describe('Model', () => {
it('should have a proper table name', async () => {
const factory = ModelFactory.get(FakeDummyModel);
expect(factory.table).toBe('fake_dummy_models');
expect(factory.make({}).table).toBe('fake_dummy_models');
2020-04-23 11:40:55 +02:00
});
it('should insert and retrieve properly', async () => {
const factory = ModelFactory.get(FakeDummyModel);
await MysqlConnectionManager.query(`DROP TABLE IF EXISTS ${(factory.table)}`);
await MysqlConnectionManager.query(`CREATE TABLE ${(factory.table)}(
2020-04-23 11:40:55 +02:00
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(256),
date DATETIME,
date_default DATETIME DEFAULT NOW(),
PRIMARY KEY(id)
)`);
const date = new Date(569985);
let instance: FakeDummyModel | null = factory.make({
2020-04-23 11:40:55 +02:00
name: 'name1',
date: date,
});
console.log(instance)
2020-04-23 11:40:55 +02:00
await instance.save();
expect(instance.id).toBe(1);
expect(instance.name).toBe('name1');
expect(instance.date?.getTime()).toBeCloseTo(date.getTime(), -4);
expect(instance.date_default).toBeDefined();
instance = await FakeDummyModel.getById(1);
2020-04-23 11:40:55 +02:00
expect(instance).toBeDefined();
expect(instance!.id).toBe(1);
expect(instance!.name).toBe('name1');
expect(instance!.date?.getTime()).toBeCloseTo(date.getTime(), -4);
expect(instance!.date_default).toBeDefined();
}, 15000);
});