98 lines
2.5 KiB
TypeScript
98 lines
2.5 KiB
TypeScript
import {expect, test, vi, it, describe, beforeEach, afterEach} from 'vitest';
|
|
import {
|
|
nextCheckInDate,
|
|
initAndSyncTables,
|
|
Nag,
|
|
CheckIn,
|
|
findGuiltyNags,
|
|
getCheckIn,
|
|
} from './service';
|
|
import {Sequelize, literal, Op} from 'sequelize';
|
|
|
|
describe('nextCheckInDate', () => {
|
|
beforeEach(() => {
|
|
vi.useFakeTimers(); // Tell vitest to use fake timers
|
|
});
|
|
afterEach(() => {
|
|
vi.useRealTimers(); // Reset date after test runs
|
|
});
|
|
it('Returns 9AM if called before 9AM that day', () => {
|
|
const now = new Date(Date.now());
|
|
let at9AM = new Date(
|
|
now.getFullYear(),
|
|
now.getMonth(),
|
|
now.getDate(),
|
|
9,
|
|
0,
|
|
);
|
|
vi.setSystemTime(
|
|
new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0),
|
|
);
|
|
expect(nextCheckInDate()).toEqual(at9AM);
|
|
});
|
|
it('Returns 9AM tomorrow if called after 9AM', () => {
|
|
const dayInMS = 24 * 60 * 60 * 1000;
|
|
const now = new Date(Date.now());
|
|
const tomorrow = new Date(Date.now() + dayInMS);
|
|
let tomorrow9AM = new Date(
|
|
tomorrow.getFullYear(),
|
|
tomorrow.getMonth(),
|
|
tomorrow.getDate(),
|
|
9,
|
|
0,
|
|
);
|
|
vi.setSystemTime(
|
|
new Date(now.getFullYear(), now.getMonth(), now.getDate(), 9, 30),
|
|
);
|
|
expect(nextCheckInDate()).toEqual(tomorrow9AM);
|
|
});
|
|
});
|
|
|
|
describe('Finding nags without check-ins', async () => {
|
|
const sequelize = new Sequelize('sqlite://:memory:');
|
|
const exampleNag = {
|
|
userId: '1234',
|
|
guildId: '1234',
|
|
channelId: '1234',
|
|
messageId: '1234',
|
|
text: 'Example nag 1',
|
|
mentionHere: false,
|
|
};
|
|
|
|
await initAndSyncTables(sequelize);
|
|
|
|
beforeEach(async () => {
|
|
vi.useFakeTimers();
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await Nag.destroy({where: {}});
|
|
await CheckIn.destroy({where: {}});
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it('Finds nags without any check-ins', async () => {
|
|
const now = new Date();
|
|
vi.setSystemTime(
|
|
new Date(now.getFullYear(), now.getMonth(), now.getDate(), 9),
|
|
);
|
|
await Nag.create(exampleNag);
|
|
const results = await findGuiltyNags();
|
|
expect(results.map(nag => nag.userId)).toEqual(['1234']);
|
|
});
|
|
|
|
it('Ignores nags with a recent check-in', async () => {
|
|
const newNag = await Nag.create(exampleNag);
|
|
newNag.save();
|
|
const currentCheckInTime = getCheckIn(9, 0);
|
|
const newCheckIn = await CheckIn.create({
|
|
nagId: newNag.id,
|
|
// 1 hour previously; i.e. we checked in before the required time
|
|
lastCheckIn: new Date(currentCheckInTime.getTime() - 60 * 60 * 1000),
|
|
});
|
|
newCheckIn.save();
|
|
const results = await findGuiltyNags();
|
|
expect(results.map(nag => nag.userId)).toEqual([]);
|
|
});
|
|
});
|