Integration tests
- Node.js course
- Advanced
- Lesson 73/83
- 5 min
Learn to write integration tests.
Integration test
An integration test verifies that multiple components work together. A unit test exercises a single function, while an integration test tries the whole chain from an HTTP request down to the database. Most real bugs show up in the interaction between components.
Example: you send a POST /users request, check the response, and verify the record was created in the database. This tests the route, the database, and the validation code together. Integration tests are slower than unit tests, but they catch real bugs better. In Node.js, the Mocha, Jest or Vitest frameworks are used. In this group you will learn HTTP integration tests with supertest, the test database, coverage, and end-to-end (E2E) tests.
Test frameworks
Popular test frameworks in Node.js: Jest, Mocha, Vitest. Jest offers both a test runner and an assertion library in one package. Mocha is only a runner; it is used with an assertion library like chai.
Example: test("addition", () => { expect(1 + 1).toBe(2); });. In Jest the test function defines a test, expect does the assertion. describe groups tests. In integration tests, the server is started in beforeAll and closed in afterAll. Tests are run with npm test. Jest also offers advanced features like parallel runs and snapshot tests. The framework choice depends on the ecosystem and the project needs.
Practice Write a simple test
Define a test with test("addition", () => { expect(1+1).toBe(2); }). Print "Test ready" with console.log.
Starter code
// Define a test with the test function
// write here
// Print "Test ready"
// write hereSample solution
test("addition", () => {
expect(1+1).toBe(2);
});
console.log("Test ready");Expected output
Test ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does an integration test verify?
POST /users → DB- Multiple components working together Correct answer
- Only a single function
- Only CSS styles
- Only HTML tags
Explanation: An integration test verifies the interaction between components.
2 Complete the test function call
____("addition", () => { expect(1+1).toBe(2); });
test("addition", () => { expect(1+1).toBe(2); });
Explanation: Write test("addition", () => { ... });.
3 Match each concept to its role
| Term | Meaning |
|---|---|
integration test |
Tests the component chain |
unit test |
Tests a single function |
Jest |
Test framework |
expect |
Does assertions |