Add cds-test-architect docs and license
Introduce a new cds-test-architect skill under skills/cds-test-architect. Adds SKILL.md (guidance, setup, patterns, anti-patterns, and checklist for writing cds.test() unit/integration tests) and EXAMPLES.md (six runnable test templates: OData CRUD, custom actions, programmatic service, PATCH/DELETE, error responses, and log capture). Also adds an Apache-2.0 LICENSE file (copyright 2026 Andrew Saba).
This commit is contained in:
parent
f458cee31a
commit
14aed76355
|
|
@ -0,0 +1,224 @@
|
|||
# Examples — CDS Backend Tests
|
||||
|
||||
Six runnable templates. Adapt the entity, service, and field names; keep the structure.
|
||||
|
||||
## 1. OData CRUD
|
||||
|
||||
Happy-path read + create against `srv/services/pay/payroll-loans.cds`. Asserts the OData layer is wired and audit fields are populated by the service.
|
||||
|
||||
```js
|
||||
// test/pay/payroll-loans.test.js
|
||||
const cds = require('@sap/cds')
|
||||
const { GET, POST, expect, data } = cds.test(__dirname + '/../..')
|
||||
|
||||
describe('PayrollLoans — OData CRUD', () => {
|
||||
beforeEach(() => data.reset())
|
||||
|
||||
it('lists loans for an authenticated user', async () => {
|
||||
const { data: body, status } = await GET('/odata/v4/payroll-loans/Loans', {
|
||||
auth: { username: 'alice' },
|
||||
})
|
||||
expect(status).to.equal(200)
|
||||
expect(body.value).to.be.an('array') // we don't pin row count — fixtures drift
|
||||
})
|
||||
|
||||
it('creates a loan and stamps audit fields', async () => {
|
||||
const { data: created, status } = await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-001', principal: 1000, currency: 'EGP' },
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
expect(status).to.equal(201)
|
||||
// assert only what this test is about — the createdBy stamp
|
||||
expect(created).to.containSubset({ createdBy: 'alice', principal: 1000 })
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## 2. Custom action
|
||||
|
||||
Bound action with auth gating. Two users, one allowed, one denied — asserts the role check, not the action body.
|
||||
|
||||
```js
|
||||
// test/pay/payroll-cycle-approvals.test.js
|
||||
const cds = require('@sap/cds')
|
||||
const { POST, expect, data } = cds.test(__dirname + '/../..')
|
||||
|
||||
describe('PayrollCycleApprovals — approveApproval action', () => {
|
||||
beforeEach(() => data.reset())
|
||||
|
||||
it('admin can approve a pending approval', async () => {
|
||||
const { status, data: body } = await POST(
|
||||
`/odata/v4/payroll-cycle-approvals/Approvals(<seeded-id>)/PayrollCycleApprovalService.approveApproval`,
|
||||
{},
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
expect(body).to.containSubset({ status: 'APPROVED' }) // payload first
|
||||
expect(status).to.equal(200) // status second
|
||||
})
|
||||
|
||||
it('viewer is rejected with 403', async () => {
|
||||
const res = await POST(
|
||||
`/odata/v4/payroll-cycle-approvals/Approvals(<seeded-id>)/PayrollCycleApprovalService.approveApproval`,
|
||||
{},
|
||||
{ auth: { username: 'bob' }, validateStatus: () => true }, // don't throw on 4xx
|
||||
)
|
||||
expect(res.status).to.equal(403)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
`validateStatus: () => true` is the escape hatch for asserting error responses — without it `cds.test` throws before the `expect` is reached.
|
||||
|
||||
## 3. Programmatic service
|
||||
|
||||
No HTTP — talk to the service through `cds.connect.to`. Best for verifying handler logic that has no external surface (e.g. an internal event handler).
|
||||
|
||||
```js
|
||||
// test/core/employee-records-service.test.js
|
||||
const cds = require('@sap/cds')
|
||||
const { expect, data } = cds.test(__dirname + '/../..')
|
||||
|
||||
describe('EmployeeRecordsService — programmatic', () => {
|
||||
let EmployeeRecords
|
||||
beforeAll(async () => { // beforeAll, not before() — works across runners
|
||||
EmployeeRecords = await cds.connect.to('EmployeeRecordsService')
|
||||
})
|
||||
beforeEach(() => data.reset())
|
||||
|
||||
it('returns records keyed by personIdExternal, never userId', async () => {
|
||||
const { Employees } = EmployeeRecords.entities
|
||||
const rows = await SELECT.from(Employees).limit(1)
|
||||
expect(rows[0]).to.have.property('personIdExternal') // SF PK rule from CLAUDE.md
|
||||
expect(rows[0]).to.not.have.property('userId') // userId is audit-only
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Programmatic tests skip the protocol layer, so they're faster and surface handler errors directly. Reach for them when the OData round-trip adds nothing to the assertion.
|
||||
|
||||
## 4. PATCH and DELETE
|
||||
|
||||
PATCH an entity and assert the `modifiedBy` stamp; DELETE and assert the record is gone.
|
||||
|
||||
```js
|
||||
// test/pay/payroll-loans.test.js (extend the same file as example 1)
|
||||
const cds = require('@sap/cds')
|
||||
const { GET, POST, PATCH, DELETE, expect, data } = cds.test(__dirname + '/../..')
|
||||
|
||||
describe('PayrollLoans — updates and deletes', () => {
|
||||
beforeEach(() => data.reset())
|
||||
|
||||
it('patches a loan principal and stamps modifiedBy', async () => {
|
||||
// create first so we have a stable ID within this test
|
||||
const { data: created } = await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-002', principal: 500, currency: 'EGP' },
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
const id = created.ID
|
||||
|
||||
const { data: patched, status } = await PATCH(
|
||||
`/odata/v4/payroll-loans/Loans(${id})`,
|
||||
{ principal: 750 },
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
expect(patched).to.containSubset({ principal: 750, modifiedBy: 'alice' })
|
||||
expect(status).to.equal(200)
|
||||
})
|
||||
|
||||
it('deletes a loan and returns 204', async () => {
|
||||
const { data: created } = await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-003', principal: 200, currency: 'EGP' },
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
const id = created.ID
|
||||
|
||||
const { status } = await DELETE(
|
||||
`/odata/v4/payroll-loans/Loans(${id})`,
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
expect(status).to.equal(204)
|
||||
|
||||
// confirm the record is gone
|
||||
const { data: body } = await GET(
|
||||
`/odata/v4/payroll-loans/Loans(${id})`,
|
||||
{ auth: { username: 'alice' }, validateStatus: () => true },
|
||||
)
|
||||
expect(body).to.containSubset({ error: { code: '404' } })
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## 5. Error response (4xx)
|
||||
|
||||
Assert validation errors, business-rule rejections, and auth failures. Use `validateStatus: () => true` so `cds.test` does not throw. Assert `error.code`, not `error.message` — codes are stable contract; messages are translated.
|
||||
|
||||
```js
|
||||
// test/pay/payroll-loans.test.js
|
||||
const cds = require('@sap/cds')
|
||||
const { POST, expect, data } = cds.test(__dirname + '/../..')
|
||||
|
||||
describe('PayrollLoans — validation errors', () => {
|
||||
beforeEach(() => data.reset())
|
||||
|
||||
it('rejects a negative principal with 400 and a stable error code', async () => {
|
||||
const res = await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-001', principal: -1, currency: 'EGP' },
|
||||
{ auth: { username: 'alice' }, validateStatus: () => true },
|
||||
)
|
||||
// payload first — tells you *why* on failure
|
||||
expect(res.data).to.containSubset({ error: { code: 'INVALID_PRINCIPAL' } })
|
||||
expect(res.status).to.equal(400)
|
||||
})
|
||||
|
||||
it('rejects unauthenticated requests with 401', async () => {
|
||||
const res = await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-001', principal: 100, currency: 'EGP' },
|
||||
{ validateStatus: () => true }, // no auth
|
||||
)
|
||||
expect(res.status).to.equal(401)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## 6. Log capture
|
||||
|
||||
Assert that a handler emits specific warnings or info entries (via `req.warn`, `req.info`) without needing a separate DB assertion. Useful for verifying business rules that warn but do not reject.
|
||||
|
||||
```js
|
||||
// test/pay/payroll-loans.test.js
|
||||
const cds = require('@sap/cds')
|
||||
const { POST, expect, data } = cds.test(__dirname + '/../..')
|
||||
|
||||
describe('PayrollLoans — ceiling warning', () => {
|
||||
let log
|
||||
beforeAll(() => { log = cds.test.log() })
|
||||
afterAll(() => log.release()) // restore normal output after the suite
|
||||
beforeEach(() => { log.clear(); return data.reset() })
|
||||
|
||||
it('warns when loan principal exceeds the ceiling', async () => {
|
||||
await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-001', principal: 999999, currency: 'EGP' },
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
// check log output contains the warning code emitted by the handler
|
||||
expect(log.output).to.contain('CEILING_EXCEEDED')
|
||||
})
|
||||
|
||||
it('does not warn for a normal loan', async () => {
|
||||
await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-002', principal: 500, currency: 'EGP' },
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
expect(log.output).to.not.contain('CEILING_EXCEEDED')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
`log.output` is a plain string of all stdout/stderr since the last `log.clear()`. Call `log.release()` in `afterAll` to stop capturing and restore normal console output for subsequent test files.
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly provide otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of Your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplateing declaration, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Andrew Saba
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
|
@ -0,0 +1,183 @@
|
|||
---
|
||||
name: cds-test-architect
|
||||
description: Unit and integration testing for the CAP backend using cds.test() from Capire. Use when the user asks for backend tests, writes a *.test.js under test/, mentions cds.test, @cap-js/cds-test, supertest-style HTTP tests for OData/actions, or wants a regression test for a CAP handler, action, or payroll/core/platform service.
|
||||
---
|
||||
|
||||
# Unit Testing the CDS Backend
|
||||
|
||||
## When this fires
|
||||
|
||||
Triggered for code under `srv/services/**` (pay, core, platform) and `srv/handlers/**`. **Not** for Playwright UI tests under `app-core/e2e/` or `app-pay/e2e/` — those have their own runners. Always co-locate backend tests under `test/<module>/<service>.test.js`, mirroring `srv/services/<module>/<service>.cds`. Tests must never live under `srv/` — that directory ships to deployments.
|
||||
|
||||
## Philosophy
|
||||
|
||||
Test through public interfaces — OData endpoints or `cds.connect.to(<Service>)` — never by reaching into handler internals or stubbing `cds.db`. Capire's mantra applies: *"The more you mock, the less you test the real thing."* A test that breaks on a rename without behavior change is a bad test.
|
||||
|
||||
Real Postgres, real `cds.test()` bootstrap, real handlers. Reset DB state between tests, don't fake it.
|
||||
|
||||
## First-run setup (once per repo)
|
||||
|
||||
Before adding the first test, run this checklist. Stop and ask the user before editing `package.json`.
|
||||
|
||||
- [ ] Install the test helper: `npm i -D @cap-js/cds-test`
|
||||
- [ ] Add to [package.json](../../../package.json) `scripts`: `"test": "cds test"`
|
||||
- [ ] Add mocked users under `cds.requires.auth` (test + development profiles):
|
||||
```json
|
||||
"auth": {
|
||||
"[development]": { "kind": "mocked" },
|
||||
"[test]": {
|
||||
"kind": "mocked",
|
||||
"users": {
|
||||
"alice": { "roles": ["admin", "payroll.approver"] },
|
||||
"bob": { "roles": ["viewer"] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
- [ ] Create `test/` at repo root (sibling of `srv/`, `db/`, `app-core/`).
|
||||
- [ ] Confirm Postgres test DB is reachable on the active profile — the skill does **not** auto-configure a `pg-test` profile.
|
||||
- [ ] Add `CDS_TEST_ENV_CHECK=y` to your test environment (`.env.test` or the `test` script in `package.json`). This causes `cds.test` to error if `cds.env` is accessed before `cds.test()` runs, which prevents plugins from loading from the wrong folder.
|
||||
|
||||
## Canonical test file
|
||||
|
||||
Every backend test file follows this shape:
|
||||
|
||||
```js
|
||||
const cds = require('@sap/cds')
|
||||
const { GET, POST, expect, data } = cds.test(__dirname + '/../..')
|
||||
|
||||
describe('<ServiceName> — <happy path concern>', () => {
|
||||
beforeEach(() => data.reset())
|
||||
|
||||
it('lists <Entity> for an authenticated user', async () => {
|
||||
const { data: body, status } = await GET('/odata/v4/<service>/<Entity>', {
|
||||
auth: { username: 'alice' },
|
||||
})
|
||||
expect(status).to.equal(200)
|
||||
expect(body.value).to.containSubset([{ /* essential fields only */ }])
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
`cds.test()` is called **once at file scope** — never inside `describe` or `beforeAll`. The path argument anchors `cds.root` at the repo so the same `db/` and `srv/services/` are picked up.
|
||||
|
||||
### Selective service boot
|
||||
|
||||
When a test file covers exactly one service, pass the service name to avoid booting unrelated services and reduce startup time:
|
||||
|
||||
```js
|
||||
const { GET, POST, expect, data } = cds.test('serve', 'PayrollLoansService').in(__dirname + '/../..')
|
||||
```
|
||||
|
||||
Use `.in()` fluently after the service name so `cds.root` is still anchored correctly.
|
||||
|
||||
## File-wide defaults
|
||||
|
||||
Use the `defaults` object to set auth, headers, or `validateStatus` once for the whole file instead of repeating them on every request. Per-request options override `defaults`.
|
||||
|
||||
```js
|
||||
const { GET, POST, expect, data, defaults } = cds.test(__dirname + '/../..')
|
||||
defaults.auth = { username: 'alice' } // all requests run as alice unless overridden
|
||||
|
||||
// override for the one test that needs a different user
|
||||
const res = await GET('/odata/v4/payroll-loans/Loans', { auth: { username: 'bob' } })
|
||||
```
|
||||
|
||||
Supported `defaults` keys: `auth`, `headers`, `baseURL`, `validateStatus`.
|
||||
|
||||
## Error responses (4xx / 5xx)
|
||||
|
||||
`cds.test` throws by default when a response has a 4xx or 5xx status, so a bare `await POST(...)` will throw before you can assert the body. Use `validateStatus: () => true` to receive the error response instead of throwing:
|
||||
|
||||
```js
|
||||
const res = await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ principal: -1 },
|
||||
{ auth: { username: 'alice' }, validateStatus: () => true },
|
||||
)
|
||||
// assert payload first — it tells you why the error happened
|
||||
expect(res.data).to.containSubset({ error: { code: 'INVALID_PRINCIPAL' } })
|
||||
expect(res.status).to.equal(400)
|
||||
```
|
||||
|
||||
Always assert `error.code`, never `error.message` — messages are translated and can change; codes are stable contract.
|
||||
|
||||
## Log capture
|
||||
|
||||
Use `cds.test.log()` to assert that handlers emit specific warnings or info messages (e.g. `req.warn`, `req.info`, structured audit entries) without writing a separate DB assertion.
|
||||
|
||||
```js
|
||||
describe('PayrollLoansService — ceiling warning', () => {
|
||||
let log
|
||||
beforeAll(() => { log = cds.test.log() })
|
||||
afterAll(() => log.release())
|
||||
beforeEach(() => { log.clear(); return data.reset() })
|
||||
|
||||
it('warns when loan exceeds ceiling', async () => {
|
||||
await POST(
|
||||
'/odata/v4/payroll-loans/Loans',
|
||||
{ personIdExternal: 'EXT-001', principal: 999999, currency: 'EGP' },
|
||||
{ auth: { username: 'alice' } },
|
||||
)
|
||||
expect(log.output).to.contain('CEILING_EXCEEDED')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
`log.output` is a plain string of everything written to stdout/stderr since the last `log.clear()`. `log.release()` stops capturing and restores normal output.
|
||||
|
||||
## `data.reset()` semantics
|
||||
|
||||
`data.reset()` drops and re-deploys the full database schema, then re-seeds from `db/data/` CSV fixtures. Every test therefore starts from a known, identical baseline. Call it in `beforeEach` — not `afterEach` — so failures leave the DB in the broken state for debugging.
|
||||
|
||||
If a test creates records it needs to reference by ID (e.g. a seeded approval for an action test), seed those IDs in your CSV fixtures under `db/data/` rather than creating them inside the test — fixture IDs are stable across resets; `POST`-created IDs are not.
|
||||
|
||||
## Test patterns
|
||||
|
||||
| Pattern | When | Example |
|
||||
| --- | --- | --- |
|
||||
| OData CRUD (GET/POST) | Validating a service entity is reachable and obeys auth | See [EXAMPLES.md](EXAMPLES.md#1-odata-crud) |
|
||||
| OData update/delete (PATCH/DELETE) | Testing write handlers, cascade deletes, optimistic lock | See [EXAMPLES.md](EXAMPLES.md#4-patch-and-delete) |
|
||||
| Custom action | Testing bound/unbound actions like `approveApproval`, `runPayrollCycle` | See [EXAMPLES.md](EXAMPLES.md#2-custom-action) |
|
||||
| Error response (4xx) | Asserting validation, auth rejection, or business-rule errors | See [EXAMPLES.md](EXAMPLES.md#5-error-response) |
|
||||
| Programmatic service | Driving a service without HTTP — best for handler unit logic | See [EXAMPLES.md](EXAMPLES.md#3-programmatic-service) |
|
||||
| Log capture | Asserting `req.warn` / `req.info` emitted by a handler | See [EXAMPLES.md](EXAMPLES.md#6-log-capture) |
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- **Do not** mock `cds.db`, `srv/handlers/**/lib/*`, the SF client, or `bullmq` queues. If you need to skip a side effect, use a feature flag in the handler, not a test mock.
|
||||
- **Do not** call `cds.test()` more than once per file — it boots a server and leaks state.
|
||||
- **Do not** use `process.chdir()`; if you need a different root, use `cds.test.in(__dirname)`.
|
||||
- **Do not** use `deep.equal` on full responses — IDs and `createdAt`/`modifiedAt` will fight you. Use `containSubset` and assert only the fields the test is *about*.
|
||||
- **Do not** assert HTTP status before payload — when a 500 comes back, the payload tells you why; the status alone hides the bug.
|
||||
- **Do not** assert `error.message` — assert `error.code`. Messages are translated and unstable; codes are contract.
|
||||
- **Do not** assert 4xx/5xx responses without `validateStatus: () => true` — `cds.test` throws on error responses by default, so the assertion is never reached.
|
||||
- **Do not** use `personIdExternal` and `userId` interchangeably — per [CLAUDE.md](../../../CLAUDE.md), `personIdExternal` is the FK; `userId` is audit-only and unstable across rehires.
|
||||
- **Do not** put tests under `srv/`, `db/`, or `app-*/`.
|
||||
- **Do not** use `before()` (Mocha-only) — use `beforeAll()` which works across runners.
|
||||
|
||||
## Checklist per test
|
||||
|
||||
- [ ] File at `test/<module>/<service>.test.js`, mirroring `srv/services/<module>/<service>.cds`
|
||||
- [ ] `cds.test()` called once at file scope
|
||||
- [ ] `data.reset()` (or explicit fixture) in `beforeEach`
|
||||
- [ ] Auth via `auth: { username }` against a user defined in the `[test]` mocked profile
|
||||
- [ ] `validateStatus: () => true` on any request expected to return 4xx/5xx
|
||||
- [ ] Asserts observable behavior — OData response, service API return value, or audit-log row — never handler internals
|
||||
- [ ] Uses `containSubset`, not `deep.equal`, for response bodies
|
||||
- [ ] Asserts `error.code`, not `error.message`, for error cases
|
||||
- [ ] No mocks for `cds.db`, SF client, or queues
|
||||
|
||||
## Verification
|
||||
|
||||
`npm test` invokes `cds test`, which runs Node's built-in `--test`. The boot-time schema-drift warner in [srv/server.js](../../../srv/server.js) is gated on `NODE_ENV !== 'test'`, so test boots stay quiet.
|
||||
|
||||
To smoke-test a new test file:
|
||||
|
||||
```
|
||||
npm test -- test/pay/payroll-loans.test.js
|
||||
```
|
||||
|
||||
If the test fails with `ECONNREFUSED` on Postgres, the test DB is not reachable — fix the profile, not the test.
|
||||
|
||||
If the test fails with `cds.env loaded before cds.test()`, ensure `cds.test()` is the first `cds` call in the file and that no top-level module import triggers `cds.env` as a side effect.
|
||||
Loading…
Reference in New Issue