Mocking replaces a real dependency with a controlled substitute. It lets a test exercise the code you care about without also running its dependencies. A mock can stand in for a function, object, module, or entire microservice. section 9.5.10
Isolation makes unit tests easier to reason about and can make them faster: a substitute can avoid database queries, network transactions, or filesystem operations. The substitute need only provide the behavior its caller needs for the test. section 9.5.10
Mock a function with Jest
Suppose square(n, multiply) calls multiply(n, n). In a Jest test, pass a mockMultiply function that checks both arguments are 2 and returns 4. Then check that square(2, mockMultiply) returns 4. The test exercises square without running the real multiplication dependency. section 9.5.10
test("can square two", () => {
const mockMultiply = (n1, n2) => { #1
expect(n1).toBe(2); #2
expect(n2).toBe(2); #2
return 4; #3
}; #1
const result = square(2, mockMultiply); #4
expect(result).toBe(4); #5
});
The test shows the complete substitution: define a mock function, pass it to the code under test, and assert the result. section 9.5.10
The same technique applies at service scale. For local development, a mock video-storage microservice replaces a cloud-backed one. It still handles storage, but saves videos to the local filesystem. Other microservices continue to work without knowing which storage implementation is running; local setup avoids a cloud connection and keeps videos on the development computer. section 10.7.2
Listing 10.3 Mock-storage microservice in the Docker Compose file
video-storage: #1
image: mock-storage
build:
context: ./mock-storage #2
dockerfile: Dockerfile-dev
container_name: video-storage
volumes:
- /tmp/mock-storage/npm-cache:/root/.npm:z
- ./mock-storage/src:/usr/src/app/src:z
- ./mock-storage/storage:/usr/src/app/storage:z #3
ports:
- "4005:80"
environment:
- PORT=80
restart: "no"
The Docker Compose entry runs the mock as the video-storage service and mounts a local directory for stored videos. section 10.7.2




















