Think about what 'in-memory' means for data persistence.
In-memory databases store data only during the test run in RAM. When the test ends, all data is lost, so each test run starts fresh.
beforeEach(async () => {
// reset database here
});Resetting means removing all tables and recreating them.
Calling dropDatabase() removes all tables, and synchronize() recreates them based on the entities, ensuring a clean database state before each test.
Think about what happens if data is not cleared between tests.
Without cleaning, data from one test remains and can cause conflicts like duplicate keys in the next test.
Think about how transactions can undo changes.
Transactions let you group changes and then roll them back, so tests do not leave data behind.
it('adds users and rolls back', async () => { await connection.transaction(async manager => { await manager.save(User, { name: 'Alice' }); await manager.save(User, { name: 'Bob' }); const countInside = await manager.count(User); expect(countInside).toBe(2); throw new Error('Rollback'); }).catch(() => {}); const countAfter = await connection.manager.count(User); expect(countAfter).toBe(0); });
What happens to data inside a transaction if an error is thrown?
The transaction rolls back all changes when an error occurs, so no users remain after the test.