| name | testing-patterns-nodejs | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| summary | Testing Couchbase Node.js applications — unit testing with Jest mocks, integration testing with testcontainers, scope/collection isolation | ||||||||||||||||
| description | Testing Couchbase Node.js applications — unit testing with Jest mocks, integration testing with testcontainers, scope/collection isolation | ||||||||||||||||
| compatibility | Node.js SDK 4.x. Jest or Mocha. | ||||||||||||||||
| metadata |
|
Mock the collection object using Jest. Install: npm install --save-dev jest.
test('getUser returns correct document', async () => {
const mockGet = jest.fn().mockResolvedValue({
content: { name: 'Alice', email: 'alice@example.com' }
});
const mockCollection = { get: mockGet };
const repo = new UserRepository(mockCollection);
const user = await repo.getUser('user::alice');
expect(user.name).toBe('Alice');
expect(mockGet).toHaveBeenCalledWith('user::alice');
});See shared mock examples for the full pattern reference.
Install: npm install --save-dev testcontainers
const { GenericContainer, Wait } = require('testcontainers');
const couchbase = require('couchbase');
describe('Integration', () => {
let container, cluster, collection;
beforeAll(async () => {
container = await new GenericContainer('couchbase/server:7.6')
.withExposedPorts(8091, 8093, 11210)
.withWaitStrategy(Wait.forHealthCheck())
.start();
// Allow cluster to initialise
await new Promise(r => setTimeout(r, 10000));
cluster = await couchbase.connect(
`couchbase://localhost:${container.getMappedPort(11210)}`,
{ username: 'Administrator', password: 'password' }
);
collection = cluster.bucket('test-bucket').defaultCollection();
}, 60000);
afterAll(() => container.stop());
test('upsert and get', async () => {
await collection.upsert('order::1', { status: 'pending' });
const result = await collection.get('order::1');
expect(result.content.status).toBe('pending');
});
});const { v4: uuidv4 } = require('uuid');
let testScope;
beforeAll(async () => {
testScope = `test_${uuidv4().replace(/-/g, '').slice(0, 8)}`;
const mgr = cluster.bucket('test-bucket').collections();
await mgr.createScope(testScope);
await mgr.createCollection({ scopeName: testScope, name: 'orders' });
});
afterAll(async () => {
await cluster.bucket('test-bucket').collections().dropScope(testScope);
});| Error | Likely cause in tests | Fix |
|---|---|---|
DocumentNotFoundError |
Key not seeded before test | Seed data in beforeAll |
BucketNotFoundError |
Test bucket not created | Create bucket in cluster init script |
UnambiguousTimeoutError |
Container not ready | Add await cluster.waitUntilReady(10000) |
AuthenticationError |
Wrong test credentials | Check username/password in connect options |