Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / CAP / Testing, Plugins, Observability & Performance

Testing, Plugins, Observability & Performance

CAP · SAP BTP ·

Open the interactive lesson →
  1. Why: quality built into the framework
  2. cds.test: the first test
  3. Test data and mocked users
  4. Service-level tests, remote services and CAP Java
  5. Linting and type safety
  6. CAP plugins: how they work and which ones to know
  7. Logging with cds.log
  8. Telemetry, SAP Cloud Logging and health checks
  9. Performance: the rules that matter
  10. Interview questions

A CAP app is not finished when it runs – it is finished when it is tested, observable and fast. This page is the home of cds.test (with Vitest – recommended since cds 10, Jest is being phased out – Mocha or the Node.js test runner), test data and mocked users, testing remote services, linting, the CAP plugin mechanism and the most useful plugins, logging with cds.log, telemetry with OpenTelemetry and SAP Cloud Logging, health checks, and performance rules for projections, $expand, pagination and indexes. Running example: the Order Approval Portal (requirement CR12). The SAP Cloud Logging service itself is explained on SAP BTP BTP Development › 05 · DevOps, Operations & Observability (Part 5); HANA query tuning on BTP Development** › 02 · SAP HANA Cloud for Developers (Part 12).

Part 1 – Why: quality built into the framework

Requirements on this page

ID

Requirement

CAP answer

CR12

Automated tests protect the approval rules (CR3, CR4, CR7)

cds.test + Vitest (cds 10; earlier Jest, now being phased out): real server, in-memory SQLite, mocked users

CR12

Find out what happened when a manager reports an error

cds.log with correlation IDs, @cap-js/telemetry traces in SAP Cloud Logging

CR12

List pages answer in well under a second, even with 1 million requests

Projections, $select / $expand, server-side paging, stored calculated elements, indexes

CR12

Audit trail and change history without custom code

Plugins: @cap-js/audit-logging, @cap-js/change-tracking

In ABAP you know ABAP Unit, test doubles for CDS (cl_cds_test_environment), SAT / ST05 and the application log. CAP has the same toolbox, but closer to the framework: a test boots the real service with an in-memory database in milliseconds, so most tests are cheap integration tests through the OData API.

Quality toolbox of a CAP app: tests (cds.test, service-level, hybrid), static checks (cds lint, cds-typer), plugins, logging, telemetry and health checks, mapped to the ABAP tools an ABAP developer knows

ABAP tool

CAP equivalent

ABAP Unit + CDS test double framework

cds.test with Vitest (cds 10; Jest being phased out) / Mocha / node --test, in-memory SQLite filled from CSV

ATC / Code Inspector

cds lint (@sap/eslint-plugin-cds) + ESLint, cds-typer for TypeScript types

Application log (SLG1)

cds.log → JSON logs → SAP Cloud Logging

ST05 / SAT / ST12

DEBUG=sql, OpenTelemetry traces (@cap-js/telemetry), HANA PlanViz

Change documents (CDHDR / CDPOS)

@cap-js/change-tracking

Read access logging / security audit log

@cap-js/audit-logging → SAP Audit Log service

Part 2 – cds.test: the first test

cds.test() starts the CAP server inside the test process (cds serve all --in-memory?): it deploys the model to in-memory SQLite, loads the CSV files and listens on a random port. You get HTTP helpers that already know the server URL.

How cds.test runs: the test file boots the CAP server in-process with in-memory SQLite and CSV data, sends HTTP requests as mocked users through the OData adapter and handlers, and resets data between tests
npm add -D @cap-js/cds-test vitest      # test helper (now a separate package) + a runner of your choice
npx vitest                            # or: node --test   |   npx mocha   |   npx jest (phased out)   |   cds test
// test/rep-service.test.js
const cds = require('@sap/cds')
const { GET, POST, data } = cds.test(__dirname + '/..')   // must come first: boots the server

describe('RepService (CR2)', () => {
beforeEach(data.reset)                                  // fresh CSV data for every test

it('lists approval requests of the rep', async () => {
const { status, data: body } = await GET('/odata/v4/rep/ApprovalRequests', {
auth: { username: 'mia', password: 'mia' }       // mocked user, see Part 3
})
expect(status).toBe(200)
expect(body.value.length).toBeGreaterThan(0)
})

it('sets status N and a deadline automatically (CR3)', async () => {
const { data: created } = await POST('/odata/v4/rep/ApprovalRequests',
{ salesOrder: '4713', customer_ID: 'C100', netAmount: 5000, currency_code: 'EUR' },
{ auth: { username: 'mia', password: 'mia' } })
expect(created.status).toBe('N')
expect(created.deadline).toBeDefined()
})
})
  • cds.test() first, before other requires of CAP sub-modules – it sets cds.root and the environment. Use cds.test.in(folder) instead of process.chdir().
  • cds.test also returns expect (Chai with chai-subset and chai-as-promised). In Jest it is only an emulation – use Jest's own expect there, or Mocha / Vitest with Chai.
  • Keep it simple: capire warns against heavy runner mocking. jest.resetModules() or fake timers can break the server – the more you mock, the less you test.
  • Axios is no longer a dependency of the test helper; if you add axios to the project it is used automatically.

Part 3 – Test data and mocked users

3.1 Test data

  • CSV files in db/data (shipped) and test/data (tests only) are loaded at every boot. Name them sap.capire.orderapproval-ApprovalRequests.csv. Design them for the tests: one request per status, one per region, one with a deadline in the past.
  • beforeEach(data.reset) restores the CSV state so tests do not depend on each other's order.

3.2 Mocked users for CR7

In development the mocked auth strategy accepts basic authentication for users you define – with roles and attributes, exactly what @restrict checks (page 07).

"cds": {
"requires": {
"auth": {
"[development]": {
"kind": "mocked",
"users": {
"mia":  { "password": "mia",  "roles": ["Rep"],     "attr": { "region": ["EMEA"] } },
"raj":  { "password": "raj",  "roles": ["Rep"],     "attr": { "region": ["APJ"] } },
"lena": { "password": "lena", "roles": ["Manager"] }
}
}
}
}
}
// test/manager-service.test.js – authorisation and validation rules
const cds = require('@sap/cds')
const { GET, POST } = cds.test(__dirname + '/..')
const mia  = { auth: { username: 'mia',  password: 'mia' } }
const lena = { auth: { username: 'lena', password: 'lena' } }
const ID = '1f0c...-a1'                      // a request in status N from test/data

describe('ManagerService', () => {
it('rejects a rep calling approve (CR7)', async () => {
await expect(POST(`/odata/v4/manager/ApprovalRequests(ID=${ID})/approve`, {}, mia))
.rejects.toThrow(/403/)
})
it('refuses a rejection without a reason (CR3)', async () => {
await expect(POST(`/odata/v4/manager/ApprovalRequests(ID=${ID})/reject`, { reason: '' }, lena))
.rejects.toThrow(/400/)
})
it('shows a rep only the own region (CR7)', async () => {
const { data } = await GET('/odata/v4/rep/ApprovalRequests?$select=region', mia)
expect(data.value.every(r => r.region === 'EMEA')).toBe(true)
})
})
  • Bound actions are addressed via the entity key; if the action name needs the service prefix in your OData version, check the $metadata – the URL form is the most common reason for 404s in tests.
  • Error messages from the test helper contain the HTTP status (e.g. 403 - Forbidden); match on the status, not on the full text.
  • Always test negative cases for every @restrict rule – a wrong where clause silently shows too much data.

Part 4 – Service-level tests, remote services and CAP Java

4.1 Calling the service API directly

Skip HTTP when you want to test logic: connect to the service and run CQL, with an explicit user.

const cds = require('@sap/cds')
cds.test(__dirname + '/..')

it('approve sets status A and writes a Decision (CR4)', async () => {
const srv = await cds.connect.to('ManagerService')
const { ApprovalRequests, Decisions } = srv.entities
const lena = new cds.User({ id: 'lena', roles: ['Manager'] })
await srv.tx({ user: lena }, tx =>
tx.send({ event: 'approve', entity: 'ApprovalRequests', params: [{ ID: '1f0c...-a1' }] }))
const req = await SELECT.one.from(ApprovalRequests, '1f0c...-a1')
expect(req.status).toBe('A')
expect(await SELECT.from(Decisions).where({ request_ID: '1f0c...-a1' })).toHaveLength(1)
})

4.2 Remote services (CR9) in tests

  • Mocked by CAP: in development a required service without credentials is served as a local mock (e.g. API_SALES_ORDER_SRV) with CSV data named after the imported entities – the same "airplane mode" as cds watch (page 09).
  • Mocked per test: prepend your own handler to the remote service, so the test controls the answer:
const S4 = await cds.connect.to('API_SALES_ORDER_SRV')
S4.prepend(() => S4.on('READ', 'A_SalesOrder', () => [
{ SalesOrder: '4711', SoldToParty: 'C100', TotalNetAmount: '12500.00', TransactionCurrency: 'EUR' }
]))
  • Integration test against the real system: cds bind --exec -- npm test (hybrid profile, real destination); run it in the pipeline nightly, not on every commit.
  • Separate mock process: cds mock srv/external/API_SALES_ORDER_SRV.csn serves the mock on its own port, so the HTTP client code of the remote service is exercised too.

4.3 CAP Java tests

  • Spring Boot tests: @SpringBootTest + @AutoConfigureMockMvc, then mockMvc.perform(get("/odata/v4/rep/ApprovalRequests")); mock users in application.yaml under cds.security.mock.users, or @WithMockUser. H2 in memory replaces SQLite. Handler code: CAP › 05 · CAP Java.

Part 5 – Linting and type safety

cds add lint          # installs ESLint + @sap/eslint-plugin-cds and adds the configuration
cds lint              # runs ESLint with the CDS rules preconfigured (model + JavaScript)
cds add typer         # cds-typer: generates TypeScript types / JSDoc for your entities (Node.js)
  • The CDS rules check the model as well as code: e.g. valid CSV headers, unknown elements in annotations, missing keys, deprecated syntax. Project-wide rules can be shown in the editor, e.g. "@sap/cds/valid-csv-header": ["warn", "show"].
  • In SAP Business Application Studio the ESLint extension is preinstalled; in VS Code install it once.
  • With cds-typer, const { ApprovalRequests } = require('#cds-models/sap/capire/orderapproval') gives code completion and catches typos in element names before runtime.
  • Put cds lint and the tests into the pipeline (cds add pipeline – BTP Development › 05).

Part 6 – CAP plugins: how they work and which ones to know

Why: audit logs, change history, attachments, telemetry and notifications are the same in every app. CAP ships them as plugins: npm add the package, annotate the model, done. A Node.js plugin is an npm package with a cds-plugin.js file; at start-up CAP scans the app's dependencies and loads every such file before the model is served, so the plugin can add handlers, services, annotations or CLI facets. Java plugins are Maven dependencies that add model parts and handlers automatically.

CAP plugin mechanism: package.json dependencies with cds-plugin.js are loaded at bootstrap, register services and handlers, and connect to local console output in development and to BTP services in production

Plugin (Node.js / Java)

Order Approval Portal use

In production talks to

@cap-js/change-tracking / built into CAP Java

History of status, netAmount, deadline with @changelog, shown in the Fiori object page

The app's own database

@cap-js/audit-logging / cds-feature-auditlog-v2

Access to customer personal data (@PersonalData)

SAP Audit Log service

@cap-js/attachments / cds-feature-attachments

Customer PO PDF on a request

HANA or object store, malware scan

@cap-js/notifications

Tell the manager a new request waits

SAP Build Work Zone notifications, e-mail

@cap-js/telemetry / built-in (Java)

Traces and metrics (Part 8)

SAP Cloud Logging, Dynatrace

@cap-js/data-inspector

Inspect data in production respecting auth and audit logging

Your app

@cap-js/ai, @cap-js/mcp, @cap-js/agents

AI features (page 13)

SAP AI Core

  • Calesi (CAP-level Service Integration): the idea behind these plugins – a BTP service is wrapped as a CAP service, so you call it with srv.send / srv.emit, it has a local mock for development and connects to the real service through bindings in production. The remote-service side of Calesi is on CAP › 09 · Remote Services.
  • @cap-js/... plugins are supported by SAP (CAP plus the service teams); @cap-js-community/... plugins are community projects and out of scope for SAP incidents. capire's "CAP Plugins" page lists the SAP ones; github.com/cap-js-community lists the community ones.

6.1 Writing your own plugin

When three apps need the same rule – e.g. "every service writes a request ID into each log line" – put it into a shared package:

// node_modules/@acme/cds-request-log/cds-plugin.js  (package.json lists @sap/cds as a peer dependency)
const cds = require('@sap/cds')
const LOG = cds.log('request-log')
cds.on('serving', srv => {                      // each provided service, once it is served
srv.before('*', req => LOG.debug(req.event, req.target?.name, 'by', req.user.id))
})

Part 7 – Logging with cds.log

const cds = require('@sap/cds')
const LOG = cds.log('order-approval')            // one logger per module or topic

this.after('approve', 'ApprovalRequests', (_, req) => {
LOG.info('request approved', { id: req.params[0].ID, by: req.user.id })
if (LOG._debug) LOG.debug('payload', req.data)   // cheap check before expensive output
})

Topic

How

Levels

silent, error, warn, info (default), debug, trace

Per module

"cds": { "log": { "levels": { "order-approval": "debug", "sql": "info" } } }

Quick debugging

DEBUG=sql cds watch (all SQL statements), DEBUG=order-approval,remote, DEBUG=all

Format

Plain text in development, JSON in production automatically (no kibana-logging facet needed since @sap/cds 7.5); opt out with cds.log.format: plain

Correlation

Each JSON line carries correlation_id from x-correlation-id (or a generated UUID), so app router, CAP and outbound calls of one request can be joined

Custom logger

cds.log.Logger = … (e.g. Winston) – rarely needed

Common mistakes: console.log (no level, no correlation ID); logging personal data, tokens or whole payloads at info; leaving debug on in production; logging inside loops over thousands of rows.

Part 8 – Telemetry, SAP Cloud Logging and health checks

Logs tell you *what* happened; traces tell you *where the time went* in one request (handler → database → S/4HANA call), and metrics show trends (CPU, memory, DB pool, queue length). CAP Node.js gets all three from the @cap-js/telemetry plugin, built on OpenTelemetry. CAP Java has OpenTelemetry support built in (Java agent) – see capire › Java › Observability.

Telemetry path: @cap-js/telemetry creates spans for CAP service calls, database statements and outbound HTTP, exports them with OTLP over gRPC to SAP Cloud Logging (ingest_otlp) or Dynatrace, next to JSON logs with the same correlation
npm add @cap-js/telemetry
# exporter dependencies for SAP Cloud Logging (OTLP over gRPC):
npm add @grpc/grpc-js @opentelemetry/exporter-trace-otlp-grpc @opentelemetry/exporter-metrics-otlp-grpc
# optional host metrics:  npm add @opentelemetry/instrumentation-host-metrics
"cds": {
"requires": {
"telemetry": { "[production]": { "kind": "to-cloud-logging" } }
}
}
# Cloud Logging instance with OpenTelemetry ingestion, bound to the CAP service (or as an mta.yaml resource)
cf create-service cloud-logging standard order-approval-logs -c '{"ingest_otlp": {"enabled": true}}'
cf bind-service order-approval-srv order-approval-logs

Kind

Exports to

Notes

telemetry-to-console (default)

Console

Development: see spans and timings in the terminal

to-cloud-logging

SAP Cloud Logging (OTLP gRPC, mTLS)

Binding found automatically; user-provided service needs the tag Cloud Logging

to-dynatrace

Dynatrace

OTLP proto exporters; or OneAgent in-process

to-jaeger / to-otlp

Jaeger (local) / any OTLP back end

Jaeger: traces only

  • What is traced: CAP service calls (handlers), database prepare / run, outbound HTTP (remote services). Metrics: process CPU / memory, db.pool, persistent queue (@sap/cds 9+), custom metrics via the OpenTelemetry API.
  • Environment switches: NO_TELEMETRY (off), OTEL_SERVICE_NAME (defaults to the package name), sampling via cds.requires.telemetry.tracing.sampler.

8.1 Health checks

  • CAP Node.js serves /health (public) → 200 { status: 'UP' } since @sap/cds 7.8. Point the platform's health check there – the generic index page at / is not served in production since CDS 8.
  • CAP Java: Spring Boot Actuator /actuator/health/liveness and /actuator/health/readiness; cds add mta / cds add kyma configure the probes.
  • Liveness failure → the platform restarts the instance; readiness failure → the instance is taken out of routing until it recovers. Don't make liveness depend on S/4HANA being reachable – a remote outage would restart all your instances in a loop.

Part 9 – Performance: the rules that matter

Performance levers in a CAP request: lean projections, $select and $expand instead of join views, server-driven paging with cds.query.limit, stored calculated elements, indexes, and avoiding N+1 queries in custom handlers

Rule

Why

Order Approval example

Lean projections

Fewer columns, fewer joins, smaller payloads

RepService.ApprovalRequests excluding { reason } for the list; details on the object page

$select / $expand instead of JOIN views

A join only runs when the client asks via $expand; filter children first

?$select=salesOrder,status&$expand=notes($top=3)

Server-driven paging

Generic READ caps results at 1000 rows by default and returns a next link

@cds.query.limit: { default: 50, max: 200 } on ApprovalRequests

Stored calculated elements

Live calculated fields cannot use indexes → full table scans

urgency : String = case when … end stored; instead of a CASE on read

No UNION views

Expensive, complex; model one entity with a type field

One Decisions entity with outcome A / R, not two entities

Associations for huge children

Draft copies whole compositions

Thousands of Notes? Association instead of composition

Indexes

Filters and sorts on large tables

@assert.unique.<name> creates a SQL UNIQUE constraint; other indexes as native .hdbindex in db/src (HANA); column options such as FUZZY SEARCH INDEX ON via @sql.append

9.1 Custom handlers: avoid N+1

// BAD: one SELECT per row (N+1) – 200 requests = 201 queries
this.after('READ', 'ApprovalRequests', async rows => {
for (const r of rows) r.noteCount = (await SELECT.from(Notes).where({ request_ID: r.ID })).length
})

// GOOD: one query for all rows
this.after('READ', 'ApprovalRequests', async rows => {
const ids = rows.map(r => r.ID)
const counts = await SELECT.from(Notes).columns('request_ID', 'count(*) as n')
.where({ request_ID: { in: ids } }).groupBy('request_ID')
const byId = Object.fromEntries(counts.map(c => [c.request_ID, c.n]))
for (const r of rows) r.noteCount = byId[r.ID] ?? 0
})
  • Even better: let the database do the work in the model – e.g. a view with count(*) and group by joined in a projection – instead of computing in JavaScript.
  • Bulk writes: INSERT.into(Notes).entries(array) – one statement, not a loop.
  • Remote calls (CR9): select only needed columns from A_SalesOrder, cache stable data (customers), set timeouts; trace them with telemetry.
  • Measure, don't guess: DEBUG=sql locally, OpenTelemetry spans in production, PlanViz / EXPLAIN PLAN on HANA (BTP Development › 02, Part 12).

Part 10 – Interview questions

Q1. What does cds.test() do?

It boots the CAP server inside the test process (cds serve all --in-memory?), deploys the model to in-memory SQLite with CSV data, listens on a random port and returns HTTP helpers (GET, POST, …), expect, data.reset and log. Runner-agnostic: Jest, Mocha, Vitest, node --test.

Q2. How do you test that only managers can approve?

Define mocked users with roles (and attributes) in the [development] auth config, call the action as a rep and expect 403, call it as a manager and expect success. Negative tests for every @restrict rule, including where conditions on attributes.

Q3. How do you test code that calls S/4HANA?

Locally CAP mocks the imported service with CSV data; per test, S4.prepend(() => S4.on('READ', ...)) returns controlled data; cds mock in a separate process tests the HTTP path; real integration tests run with cds bind --exec -- npm test in a nightly pipeline.

Q4. What is a CAP plugin technically?

In Node.js an npm package with a cds-plugin.js that CAP loads automatically from the app's dependencies at bootstrap; it can register services, handlers, annotations and cds add facets. In Java a Maven dependency that adds model and handlers.

Q5. Name three plugins and what they replace in ABAP.

@cap-js/change-tracking ≈ change documents, @cap-js/audit-logging ≈ read access logging / security audit log (via SAP Audit Log service), @cap-js/attachments ≈ GOS attachments; plus @cap-js/telemetry for tracing.

Q6. Why cds.log instead of console.log?

Levels per module configurable without code changes, DEBUG= switches, automatic JSON format in production with correlation_id, so one request can be followed across app router, CAP and remote calls in SAP Cloud Logging.

Q7. How do traces get from a CAP app into SAP Cloud Logging?

@cap-js/telemetry with kind to-cloud-logging and the gRPC OTLP exporters; the Cloud Logging instance has ingest_otlp enabled and is bound to the app, so the binding provides the OTLP endpoint and mTLS certificates.

Q8. What does CAP do by default to protect the database from huge reads?

Generic READ handlers cap results at 1000 rows and return a next link; @cds.query.limit (or cds.query.limit config) sets default and max per entity, service or globally.

Q9. Why are live calculated fields a performance risk?

They are computed on every read and cannot use indexes, so filters and sorts on them scan the table. Use stored calculated elements (calculated on write) or disable sorting / filtering on them.

Q10. What is the difference between liveness and readiness?

Liveness failure → restart; readiness failure → removed from routing temporarily. CAP Node.js offers /health; CAP Java uses the Actuator liveness / readiness endpoints.

Q11. Scenario: managers say the approval list takes 8 seconds. How do you analyse it?

Reproduce with the same $filter / $expand; check telemetry spans to see whether time is in the database, a handler or a remote call; DEBUG=sql for the statements; look for N+1 loops in after READ handlers, live calculated fields in filters, missing paging, big $expand; then PlanViz on HANA and an index or a stored element.

Q12. Scenario: a test passes locally but the same request fails on HANA Cloud. Why can that happen?

SQLite and HANA differ in case sensitivity, sorting, type strictness and native functions; native HANA objects do not exist on SQLite. Run the suite against HANA in hybrid mode (cds bind --exec -- npm test) in the pipeline before releases.

🏠 Start Here · ◀ 11 · Multitenancy & SaaS · 13 · CAP & AI ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP