Test database
- Node.js course
- Advanced
- Lesson 75/83
- 5 min
Learn test databases and fixtures.
Test database
If integration tests write to the real database, they corrupt the data. That is why a separate test database is used. The test database is cleaned before each test; this way tests run independently of each other.
Example: production uses the myapp database, tests use myapp_test. When process.env.NODE_ENV === "test", the app connects to the test database. Before each test, tables are cleaned in beforeEach. This makes tests reproducible. The test database must have the same structure as the production database; migrations are applied to both. Using a test database lets integration tests run safely without affecting production.
Cleaning with beforeEach
Cleaning the database before each test prevents tests from affecting each other. In Jest, beforeEach is called before each test; here you clear tables.
Example: beforeEach(async () => { await db.query("DELETE FROM users"); });. This empties the users table before each test. So a record added by one test does not affect another. afterEach is also called after each test; sometimes cleaning is done there. Cleaning makes tests order-independent. Tests should be runnable in any order; any order should work. This is the foundation of test reliability. Without a test database, this is not possible.
Practice Add test cleaning
Define test cleaning with beforeEach(async () => { console.log("Cleaned"); }). Print "Cleaning ready" with console.log.
Starter code
// Define cleaning with beforeEach
// write here
// Print "Cleaning ready"
// write hereSample solution
beforeEach(async () => {
console.log("Cleaned");
});
console.log("Cleaning ready");Expected output
Cleaning ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each concept to its role
| Term | Meaning |
|---|---|
test database |
Tests' data |
NODE_ENV=test |
Sets test mode |
beforeEach |
Cleans before each test |
myapp_test |
Test database name |
2 Why use a test database?
NODE_ENV=test → myapp_test- To not corrupt production data Correct answer
- For faster network
- For more colorful logs
- For less memory
Explanation: A test database protects production data.
3 Complete the beforeEach call
____(async () => { await db.query("DELETE FROM users"); });
beforeEach(async () => { await db.query("DELETE FROM users"); });
Explanation: beforeEach is called before each test.