Use postgres with useFakeTimer #798
-
Hello everyone! At my job we've been using postgres for a few months and it works great, congrats 👍 Recently we hit a wall: in a test (vitest) we use Does anyone have an idea why that's the case and how to fix it? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
To address the issue of 1. Set Up Test EnvironmentFirst, ensure you have the necessary dependencies installed: npm install --save-dev vitest pg 2. Initialize PostgreSQL ConnectionIn your test file, establish a connection to your PostgreSQL database using the const { Pool } = require('pg');
const pool = new Pool({
user: 'your_username',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432, // Default PostgreSQL port
}); 3. Write Test CasesWrite your test cases using const { useFakeTimers } = require('vitest');
describe('PostgreSQL Tests', () => {
let clock;
before(() => {
// Initialize fake timers before tests
clock = useFakeTimers();
});
after(() => {
// Restore original timers after tests
clock.restore();
});
it('should perform a database query', async () => {
// Mock PostgreSQL query
const res = await pool.query('SELECT NOW()');
console.log('Current time from PostgreSQL:', res.rows[0].now);
});
}); 4. Troubleshoot Blocking IssueIf the tests are timing out due to
ConclusionBy following these steps and troubleshooting techniques, you should be able to identify and resolve the issue of |
Beta Was this translation helpful? Give feedback.
-
For the record, it works with this code: import postgres from 'postgres';
import { afterAll, beforeAll, test, vi } from 'vitest';
const pgClient = postgres(process.env.PG_CONNECTION_STRING, {});
beforeAll(() => {
vi.useFakeTimers({toFake: ['Date']}); // mock only what you need
vi.setSystemTime(new Date());
});
afterAll(() => {
vi.useRealTimers();
});
test('lock', async () => {
try {
console.log('before call');
const result2 = await pgClient`SELECT * FROM "user"`;
console.log('after call');
} catch (e) {
console.log('catch');
}
console.log('end');
}, 20_000); I suppose useFakeTimers mocks something that is used by postgres in a way that disturbs postgres, thus creating an issue. |
Beta Was this translation helpful? Give feedback.
For the record, it works with this code:
I suppose useFakeTimers mocks something that is used by postgres in…