Node.js
Integration tests
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.
Exercise Write a simple test
Define a test with test("addition", () => { expect(1+1).toBe(2); }). Print "Test ready" with console.log.
Show example solution
test("addition", () => {
expect(1+1).toBe(2);
});
console.log("Test ready");
Test yourself
-
What does an integration test verify?
POST /users → DB
- Multiple components working together
- Only a single function
- Only CSS styles
- Only HTML tags
Show answer
Multiple components working together — An integration test verifies the interaction between components.
-
Complete the test function call
____("addition", () => { expect(1+1).toBe(2); });
Show answer
test("addition", () => { expect(1+1).toBe(2); });
-
Match each concept to its role
- integration test
- Tests the component chain
- unit test
- Tests a single function
- Jest
- Test framework
- expect
- Does assertions
Next lesson: Supertest