Conversation
Add middleware reference documentation covering AOP (recommended) and function-style (legacy) patterns. Update egg-controller SKILL.md with middleware decision tree, quick reference, and troubleshooting entries. Update egg entry skill routing for middleware-related queries. Add 8 middleware eval cases (id 26-33). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Exclude eval/, CLAUDE.md, PLAN.md and other non-skill files from the npm package by explicitly listing only skill directories. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add unittest skill covering HTTP test, Service/DI test, Mock patterns, BackgroundTaskHelper test, and EventBus test. Update entry skill routing for unittest queries. Add cross-references from egg-controller and egg-core skills. Add 24 eval cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly expands the framework's capabilities by introducing robust middleware support for controllers and a comprehensive guide for unit testing. These additions aim to improve the extensibility of API endpoints and provide clear, detailed instructions for developers to write effective tests across various components, ultimately enhancing code quality and maintainability. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. Footnotes
|
📝 WalkthroughWalkthroughAdds comprehensive unit-testing docs as a new Changes
Sequence Diagram(s)sequenceDiagram
participant Client as "Client"
participant Egg as "Egg App"
participant FuncMw as "Function Middleware\n(koa-style)"
participant AOPMw as "AOP Middleware\n@Advice/@Middleware"
participant Controller as "Controller"
participant Service as "Service"
Client->>Egg: HTTP request
Egg->>FuncMw: run function-style middleware (outer->inner)
FuncMw->>AOPMw: next -> enter AOP phase
AOPMw->>Controller: around() -> invoke controller
Controller->>Service: call service
Service-->>Controller: result
Controller-->>AOPMw: return value
AOPMw-->>FuncMw: exit AOP, return
FuncMw-->>Egg: finish middleware chain
Egg-->>Client: HTTP response
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Deploying egg with
|
| Latest commit: |
fe6a611
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://be027b0e.egg-cci.pages.dev |
| Branch Preview URL: | https://feat-skills-middleware-unitt.egg-cci.pages.dev |
Deploying egg-v3 with
|
| Latest commit: |
fe6a611
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://6b5c8826.egg-v3.pages.dev |
| Branch Preview URL: | https://feat-skills-middleware-unitt.egg-v3.pages.dev |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## next #5836 +/- ##
==========================================
- Coverage 85.64% 85.62% -0.02%
==========================================
Files 665 665
Lines 13004 13004
Branches 1495 1495
==========================================
- Hits 11137 11135 -2
- Misses 1743 1745 +2
Partials 124 124 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 Nitpick comments (4)
packages/skills/egg-unittest/references/mock.md (1)
61-71: Spy pattern differs from mock pattern.Note the spy example (lines 68-70) accesses
NotifyService.prototype.senddirectly for assertions rather than a captured mock function. This is a different approach that assumesmm.spy()augments the target prototype method. Ensure both patterns are documented consistently, or clarify when to use which approach.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/skills/egg-unittest/references/mock.md` around lines 61 - 71, The example mixes spy and mock styles by asserting directly on NotifyService.prototype.send after calling mm.spy(); update the example or docs to be consistent: either capture the spy returned by mm.spy(mmSpy = mm.spy(NotifyService.prototype, 'send')) and assert on mmSpy.called and mmSpy.lastCalledArguments, or add a clear note explaining that mm.spy mutates NotifyService.prototype.send in-place so later assertions use that prototype method; reference mm.spy, NotifyService.prototype.send, OrderService.create and app.getEggObject(OrderService) in the clarification.packages/skills/eval/evals-egg-unittest.json (1)
131-156: Consider adding one more test case each for background-task and eventbus.Per coding guidelines, evaluation design should cover "at least 5+ test cases per reference document." Currently:
background-task-test: 4 cases (evals 17-20)eventbus-test: 4 cases (evals 21-24)Consider adding one more case to each section for complete coverage. Potential additions:
- Background task: Testing timeout configuration or error handling
- EventBus: Testing cork/uncork buffering or multi-handler scenarios
Also applies to: 157-182
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/skills/eval/evals-egg-unittest.json` around lines 131 - 156, Add one additional eval entry to the background-task group and one to the eventbus group in the JSON test file so each group has at least 5 test cases; for background-task add a case that verifies timeout or error handling (e.g., call app.httpRequest to trigger a task that throws or times out and assert app.backgroundTasksFinished() rejects or that an error state is recorded), referencing existing patterns like the test that uses app.httpRequest(), TimerUtil.sleep, and CountService to mirror structure; for eventbus add a case covering cork/uncork buffering or multiple handlers (publish events via EventBus, assert all handlers ran and ordering/buffering behavior), ensure each new eval object includes id, prompt, expected_output and, when needed, a files array with a test file under test/... that imports app from '@eggjs/mock/bootstrap' and uses the same helper symbols (app.backgroundTasksFinished(), app.getEggObject, EventBus) so the suite reaches 5+ cases per section.packages/skills/egg-unittest/SKILL.md (1)
97-114: Add language identifier to fenced code block.The decision tree code block is missing a language identifier. While this is a text-based decision tree (not actual code), adding a language identifier satisfies the linter and improves rendering consistency.
📝 Suggested fix
-``` +```text 要测什么?🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/skills/egg-unittest/SKILL.md` around lines 97 - 114, The fenced code block in SKILL.md containing the decision tree lacks a language identifier; update the opening fence for that block (the triple backticks before "要测什么?") to include a language label such as "text" (i.e., change ``` to ```text) so the linter and renderer treat it consistently; no other changes to the block content are needed—locate the block in SKILL.md and modify the opening fence accordingly.packages/skills/egg-unittest/references/http-test.md (1)
98-98: Minor grammar suggestion.Consider fixing the Chinese grammar: "灵活的断言" → "灵活地断言" (adverb modifier should use "地").
📝 Suggested fix
-使用 `result` 做更灵活的断言: +使用 `result` 做更灵活地断言:🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/skills/egg-unittest/references/http-test.md` at line 98, Update the Chinese grammar in the markdown snippet that currently reads "使用 `result` 做更灵活的断言:" to use the adverbial particle "地"—change it to "使用 `result` 做更灵活地断言:" so the modifier is grammatically correct; locate this exact phrase in packages/skills/egg-unittest/references/http-test.md and replace it accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/skills/egg-unittest/references/http-test.md`:
- Line 98: Update the Chinese grammar in the markdown snippet that currently
reads "使用 `result` 做更灵活的断言:" to use the adverbial particle "地"—change it to "使用
`result` 做更灵活地断言:" so the modifier is grammatically correct; locate this exact
phrase in packages/skills/egg-unittest/references/http-test.md and replace it
accordingly.
In `@packages/skills/egg-unittest/references/mock.md`:
- Around line 61-71: The example mixes spy and mock styles by asserting directly
on NotifyService.prototype.send after calling mm.spy(); update the example or
docs to be consistent: either capture the spy returned by mm.spy(mmSpy =
mm.spy(NotifyService.prototype, 'send')) and assert on mmSpy.called and
mmSpy.lastCalledArguments, or add a clear note explaining that mm.spy mutates
NotifyService.prototype.send in-place so later assertions use that prototype
method; reference mm.spy, NotifyService.prototype.send, OrderService.create and
app.getEggObject(OrderService) in the clarification.
In `@packages/skills/egg-unittest/SKILL.md`:
- Around line 97-114: The fenced code block in SKILL.md containing the decision
tree lacks a language identifier; update the opening fence for that block (the
triple backticks before "要测什么?") to include a language label such as "text"
(i.e., change ``` to ```text) so the linter and renderer treat it consistently;
no other changes to the block content are needed—locate the block in SKILL.md
and modify the opening fence accordingly.
In `@packages/skills/eval/evals-egg-unittest.json`:
- Around line 131-156: Add one additional eval entry to the background-task
group and one to the eventbus group in the JSON test file so each group has at
least 5 test cases; for background-task add a case that verifies timeout or
error handling (e.g., call app.httpRequest to trigger a task that throws or
times out and assert app.backgroundTasksFinished() rejects or that an error
state is recorded), referencing existing patterns like the test that uses
app.httpRequest(), TimerUtil.sleep, and CountService to mirror structure; for
eventbus add a case covering cork/uncork buffering or multiple handlers (publish
events via EventBus, assert all handlers ran and ordering/buffering behavior),
ensure each new eval object includes id, prompt, expected_output and, when
needed, a files array with a test file under test/... that imports app from
'@eggjs/mock/bootstrap' and uses the same helper symbols
(app.backgroundTasksFinished(), app.getEggObject, EventBus) so the suite reaches
5+ cases per section.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d1cb6101-592f-4b8c-baf9-a094c4555e9b
📒 Files selected for processing (15)
packages/skills/egg-controller/SKILL.mdpackages/skills/egg-controller/references/middleware.mdpackages/skills/egg-core/SKILL.mdpackages/skills/egg-core/references/background-task.mdpackages/skills/egg-core/references/eventbus.mdpackages/skills/egg-unittest/SKILL.mdpackages/skills/egg-unittest/references/background-task-test.mdpackages/skills/egg-unittest/references/eventbus-test.mdpackages/skills/egg-unittest/references/http-test.mdpackages/skills/egg-unittest/references/mock.mdpackages/skills/egg-unittest/references/service-test.mdpackages/skills/egg/SKILL.mdpackages/skills/eval/evals-egg-controller.jsonpackages/skills/eval/evals-egg-unittest.jsonpackages/skills/package.json
There was a problem hiding this comment.
Pull request overview
This PR expands the @eggjs/skills documentation set by adding guidance for controller middleware and unit testing, updates the entry egg skill routing to point users to the right skill, and tightens what files are published for the @eggjs/skills npm package.
Changes:
- Add a new
egg-unittestskill with reference docs for HTTP tests, DI/service tests, mocking, BackgroundTask, and EventBus testing, plus corresponding eval cases. - Add a middleware reference to
egg-controllerand extend controller eval coverage to include middleware scenarios. - Update
egg/SKILL.mdrouting to include unittest/middleware queries and narrowpackages/skillspublished files to skill directories.
Reviewed changes
Copilot reviewed 15 out of 15 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/skills/package.json | Restrict npm published files to skill directories only. |
| packages/skills/eval/evals-egg-unittest.json | Add new unittest eval dataset. |
| packages/skills/eval/evals-egg-controller.json | Extend controller evals to include middleware scenarios. |
| packages/skills/egg/SKILL.md | Route “middleware” and “unittest” intents to the right skills. |
| packages/skills/egg-unittest/SKILL.md | New skill entry for Egg unit testing. |
| packages/skills/egg-unittest/references/http-test.md | New HTTP testing reference. |
| packages/skills/egg-unittest/references/service-test.md | New DI/service testing reference. |
| packages/skills/egg-unittest/references/mock.md | New mocking patterns reference. |
| packages/skills/egg-unittest/references/background-task-test.md | New BackgroundTask testing reference. |
| packages/skills/egg-unittest/references/eventbus-test.md | New EventBus testing reference. |
| packages/skills/egg-core/references/eventbus.md | Replace embedded testing section with link to egg-unittest reference. |
| packages/skills/egg-core/references/background-task.md | Add link to egg-unittest BackgroundTask testing reference. |
| packages/skills/egg-core/SKILL.md | Add cross-reference to egg-unittest skill. |
| packages/skills/egg-controller/references/middleware.md | New middleware guide (function-style + AOP). |
| packages/skills/egg-controller/SKILL.md | Extend controller skill to cover middleware and link to reference. |
You can also share your feedback on Copilot code review. Take the survey.
| ### Service 测试 | ||
|
|
||
| ```typescript | ||
| import assert from 'node:assert'; | ||
| import { app } from '@eggjs/mock/bootstrap'; | ||
| import { UserService } from '../app/modules/user/UserService.ts'; | ||
|
|
||
| describe('test/service/user.test.ts', () => { | ||
| it('should get user', async () => { | ||
| const userService = await app.getEggObject(UserService); | ||
| const user = await userService.getById('1'); | ||
| assert(user); | ||
| assert.equal(user.name, 'test'); | ||
| }); | ||
| }); |
|
|
||
| ### AOP 写法(推荐) | ||
|
|
||
| 使用 `@Advice()` 装饰器定义类,实现 `IAdvice` 的 `around` 方法,写法与 Koa 中间件一致(`next` 调用目标方法)。Advice 本身是 Proto,支持 `@Inject` 注入依赖。`around` 中可以修改入参(`ctx.args`)和返回值: |
| @Middleware(methodMw) | ||
| async hello() {} | ||
|
|
||
| // 多个 @Middleware 从上到下执行 |
| // countMw → timeMw → LogAdvice → AuthAdvice → hello() | ||
| // (先所有函数式,再所有 AOP,与装饰器书写顺序无关) |
| { | ||
| "id": 33, | ||
| "prompt": "帮我看看这个 Controller 上的中间件执行顺序是什么样的", | ||
| "expected_output": "函数式和 AOP 分属两个独立执行阶段:先执行所有函数式中间件(类级别 countMw → 方法级别 timeMw),再执行所有 AOP 中间件(类级别 LogAdvice → 方法级别 AuthAdvice),最后执行 hello()。即 countMw → timeMw → LogAdvice → AuthAdvice → hello(),与装饰器书写顺序无关", |
| ```typescript | ||
| import { app, mm } from '@eggjs/mock/bootstrap'; | ||
| import { UserService } from '../app/modules/user/UserService.ts'; | ||
| import { OrderService } from '../app/modules/order/OrderService.ts'; | ||
|
|
||
| describe('OrderService', () => { | ||
| it('should mock user service', async () => { | ||
| mm(UserService.prototype, 'getById', async () => { | ||
| return { id: '1', name: 'mocked user' }; | ||
| }); | ||
|
|
||
| const orderService = await app.getEggObject(OrderService); | ||
| const result = await orderService.createForUser('1'); | ||
| assert.equal(result.userName, 'mocked user'); | ||
| }); |
| ```typescript | ||
| import { app, mm } from '@eggjs/mock/bootstrap'; | ||
| import { OrderService } from '../app/modules/order/OrderService.ts'; | ||
| import { PaymentService } from '../app/modules/payment/PaymentService.ts'; | ||
|
|
||
| describe('OrderService', () => { | ||
| it('should create order with mocked payment', async () => { | ||
| mm(PaymentService.prototype, 'charge', async () => { | ||
| return { transactionId: 'mock-tx-001' }; | ||
| }); | ||
|
|
||
| const orderService = await app.getEggObject(OrderService); | ||
| const order = await orderService.create({ productId: '1', amount: 100 }); | ||
| assert.equal(order.transactionId, 'mock-tx-001'); | ||
| }); |
| ```typescript | ||
| import { app } from '@eggjs/mock/bootstrap'; | ||
|
|
||
| it('should validate response', () => { | ||
| return app.httpRequest() | ||
| .get('/api/users/1') | ||
| .expect(200) // 只校验状态码 | ||
| .expect({ id: '1', name: 'test' }) // 只校验 body(deepStrictEqual) | ||
| .expect(200, { id: '1', name: 'test' }) // 状态码 + body 合并 | ||
| .expect('hello world') // body 字符串匹配 | ||
| .expect(/hello/) // body 正则匹配 | ||
| .expect('content-type', /json/) // header 匹配 | ||
| .expect([200, 302]) // 多状态码匹配(任一即可) | ||
| .expect(res => { // 自定义断言函数 | ||
| assert(res.body.id); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Code Review
This pull request is a great addition, introducing comprehensive 'skills' for Middleware and Unit Testing in the EGG framework. The new documentation is well-structured, detailed, and the inclusion of evaluation files is a solid practice. I have one minor suggestion for improvement in a code example within the new middleware documentation.
|
|
||
| const start = Date.now(); | ||
| const result = await next(); | ||
| this.logger.info('%s cost %dms', ctx.method, Date.now() - start); |
There was a problem hiding this comment.
In this AOP example, ctx.method is used directly in the logger. Assuming ctx is of type AdviceContext and ctx.method is a JoinPoint object (which represents the intercepted method), this will likely be stringified to [object Object]. To log the actual method name, you should probably use ctx.method.name.
| this.logger.info('%s cost %dms', ctx.method, Date.now() - start); | |
| this.logger.info('%s cost %dms', ctx.method.name, Date.now() - start); |
- middleware.md: fix decorator execution order (bottom-up, not top-down) - middleware.md: clarify mixed mode ordering description - mock.md, service-test.md, http-test.md: add missing assert imports Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/skills/egg-unittest/references/http-test.md`:
- Line 99: 将第99行的句子“使用 `result` 做更灵活的断言”改为更符合语法的表述“使用 `result` 更灵活地断言”;在文件
packages/skills/egg-unittest/references/http-test.md 中定位该句并替换为新句子以保持语句流畅与一致性。
- Around line 13-160: Add the missing reference sections: 1) File conventions —
describe config/config.default.ts (e.g. security.csrf enable),
controller/service/test locations and naming rules (refer to
config/config.default.ts, app/controller/user.ts, app/service/user.ts,
test/controller/user.test.ts); 2) One complete end-to-end chain example showing
config → controller → service → tests (describe the sample entries for
config/config.default.ts, a controller class in app/controller/user.ts, a
service in app/service/user.ts, and the test using app.httpRequest() +
app.mockCsrf() in test/controller/user.test.ts); 3) Append a decorator
quick-reference index table listing decorators and brief usage locations
(include `@HTTPController`, `@Get/`@Post, `@Body/`@Query/@Param) as the final section.
Ensure the new sections are concise and placed after the existing end-to-end
example.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f49f2831-ca67-4e4a-aadd-c1cb544301f1
📒 Files selected for processing (4)
packages/skills/egg-controller/references/middleware.mdpackages/skills/egg-unittest/references/http-test.mdpackages/skills/egg-unittest/references/mock.mdpackages/skills/egg-unittest/references/service-test.md
✅ Files skipped from review due to trivial changes (3)
- packages/skills/egg-unittest/references/service-test.md
- packages/skills/egg-controller/references/middleware.md
- packages/skills/egg-unittest/references/mock.md
| ## 基本用法 | ||
|
|
||
| 通过 `app.httpRequest()` 发起 HTTP 请求,返回 SuperTest 对象: | ||
|
|
||
| ```typescript | ||
| import { app } from '@eggjs/mock/bootstrap'; | ||
|
|
||
| describe('UserController', () => { | ||
| it('should GET /api/users', () => { | ||
| return app.httpRequest() | ||
| .get('/api/users') | ||
| .expect(200) | ||
| .expect({ users: [] }); | ||
| }); | ||
| }); | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## POST 请求 + CSRF | ||
|
|
||
| POST/PUT/DELETE 请求需要先调用 `app.mockCsrf()` 跳过 CSRF 校验: | ||
|
|
||
| ```typescript | ||
| it('should POST /api/users', () => { | ||
| app.mockCsrf(); | ||
| return app.httpRequest() | ||
| .post('/api/users') | ||
| .send({ name: 'test', email: 'test@example.com' }) | ||
| .expect(200) | ||
| .expect({ id: '1', name: 'test' }); | ||
| }); | ||
| ``` | ||
|
|
||
| 表单提交使用 `.type('form')`: | ||
|
|
||
| ```typescript | ||
| it('should POST form data', () => { | ||
| app.mockCsrf(); | ||
| return app.httpRequest() | ||
| .post('/api/login') | ||
| .type('form') | ||
| .send({ username: 'admin', password: '123' }) | ||
| .expect(200); | ||
| }); | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 请求构造 | ||
|
|
||
| ```typescript | ||
| app.httpRequest() | ||
| .get('/api/users') | ||
| .set('Authorization', 'Bearer token123') // 设置 header | ||
| .set('Accept', 'application/json') // 设置 Accept | ||
| .query({ page: 1, limit: 10 }) // 查询参数 | ||
| .expect(200); | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 响应断言 | ||
|
|
||
| 使用 `.expect()` 链式断言: | ||
|
|
||
| ```typescript | ||
| import assert from 'node:assert'; | ||
| import { app } from '@eggjs/mock/bootstrap'; | ||
|
|
||
| it('should validate response', () => { | ||
| return app.httpRequest() | ||
| .get('/api/users/1') | ||
| .expect(200) // 只校验状态码 | ||
| .expect({ id: '1', name: 'test' }) // 只校验 body(deepStrictEqual) | ||
| .expect(200, { id: '1', name: 'test' }) // 状态码 + body 合并 | ||
| .expect('hello world') // body 字符串匹配 | ||
| .expect(/hello/) // body 正则匹配 | ||
| .expect('content-type', /json/) // header 匹配 | ||
| .expect([200, 302]) // 多状态码匹配(任一即可) | ||
| .expect(res => { // 自定义断言函数 | ||
| assert(res.body.id); | ||
| }); | ||
| }); | ||
| ``` | ||
|
|
||
| 使用 `result` 做更灵活的断言: | ||
|
|
||
| ```typescript | ||
| import assert from 'node:assert'; | ||
| import { app } from '@eggjs/mock/bootstrap'; | ||
|
|
||
| it('should validate response', async () => { | ||
| const result = await app.httpRequest() | ||
| .get('/api/users/1'); | ||
|
|
||
| assert.equal(result.status, 200); | ||
| assert.equal(result.body.name, 'test'); | ||
| assert(result.body.id); | ||
| assert.match(result.headers['content-type'], /json/); | ||
| }); | ||
| ``` | ||
|
|
||
| 完整的请求构造和断言 API 可查看项目 node_modules 中 `@eggjs/supertest` 的类型定义。 | ||
|
|
||
| --- | ||
|
|
||
| ## 端到端示例 | ||
|
|
||
| ```typescript | ||
| import assert from 'node:assert'; | ||
| import { app } from '@eggjs/mock/bootstrap'; | ||
|
|
||
| describe('test/controller/user.test.ts', () => { | ||
| describe('GET /api/users/:id', () => { | ||
| it('should return user', () => { | ||
| return app.httpRequest() | ||
| .get('/api/users/1') | ||
| .expect(200) | ||
| .expect({ id: '1', name: 'test' }); | ||
| }); | ||
|
|
||
| it('should return 404 when user not found', () => { | ||
| return app.httpRequest() | ||
| .get('/api/users/999') | ||
| .expect(404); | ||
| }); | ||
| }); | ||
|
|
||
| describe('POST /api/users', () => { | ||
| it('should create user', () => { | ||
| app.mockCsrf(); | ||
| return app.httpRequest() | ||
| .post('/api/users') | ||
| .send({ name: 'new user', email: 'new@example.com' }) | ||
| .expect(201); | ||
| }); | ||
|
|
||
| it('should return 422 with invalid params', () => { | ||
| app.mockCsrf(); | ||
| return app.httpRequest() | ||
| .post('/api/users') | ||
| .send({ name: '' }) | ||
| .expect(422); | ||
| }); | ||
| }); | ||
| }); | ||
| ``` |
There was a problem hiding this comment.
Complete the required reference structure (file conventions + full E2E chain + ending quick-reference table).
This doc is useful, but it currently misses required sections for references under this path:
- file conventions (目录结构/命名规则/配置位置),
- one complete chain example (
config → controller → service → tests), - a decorator quick-reference table at the end.
📌 Suggested structure patch
## 基本用法
...
+---
+
+## 文件约定(推荐)
+
+| 类型 | 位置 | 命名建议 |
+| --- | --- | --- |
+| Controller | `app/controller/*.ts` | 资源语义命名,如 `user.ts` |
+| Service | `app/service/*.ts` | 与领域一致,如 `user.ts` |
+| 路由配置 | `app/router.ts` 或对应路由文件 | RESTful 风格 |
+| 测试文件 | `test/controller/*.test.ts` | 与被测 controller 对齐 |
+| 测试夹具/初始化 | `test/fixtures/**` | 按场景分目录 |
+
+---
+
+## 端到端链路示例(config → controller → service → tests)
+
+```typescript
+// 1) config: config/config.default.ts(示例)
+// export default { security: { csrf: { enable: true } } };
+
+// 2) controller: app/controller/user.ts(示例)
+// 3) service: app/service/user.ts(示例)
+// 4) test: test/controller/user.test.ts(示例,使用 app.httpRequest + app.mockCsrf)
+```
+
...
## 端到端示例
...
+---
+
+## 装饰器速查(仅索引)
+
+| 装饰器 | 用途 | 典型位置 |
+| --- | --- | --- |
+| `@HTTPController` | 定义 HTTP 控制器 | Controller 类 |
+| `@Get` / `@Post` | 路由方法声明 | Controller 方法 |
+| `@Body` / `@Query` / `@Param` | 请求参数获取 | Controller 方法参数 |As per coding guidelines "Reference documents must ... Include file conventions ... end-to-end complete examples (config → controller → Service → tests), and decorator reference tables at the end for quick lookup only."
🧰 Tools
🪛 LanguageTool
[uncategorized] ~99-~99: 动词的修饰一般为‘形容词(副词)+地+动词’。您的意思是否是:灵活"地"断言
Context: ...y.id); }); }); 使用 `result` 做更灵活的断言: typescript import assert from 'n...
(wb4)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/skills/egg-unittest/references/http-test.md` around lines 13 - 160,
Add the missing reference sections: 1) File conventions — describe
config/config.default.ts (e.g. security.csrf enable), controller/service/test
locations and naming rules (refer to config/config.default.ts,
app/controller/user.ts, app/service/user.ts, test/controller/user.test.ts); 2)
One complete end-to-end chain example showing config → controller → service →
tests (describe the sample entries for config/config.default.ts, a controller
class in app/controller/user.ts, a service in app/service/user.ts, and the test
using app.httpRequest() + app.mockCsrf() in test/controller/user.test.ts); 3)
Append a decorator quick-reference index table listing decorators and brief
usage locations (include `@HTTPController`, `@Get/`@Post, `@Body/`@Query/@Param) as
the final section. Ensure the new sections are concise and placed after the
existing end-to-end example.
| }); | ||
| ``` | ||
|
|
||
| 使用 `result` 做更灵活的断言: |
There was a problem hiding this comment.
Polish wording at Line 99 for grammar consistency.
建议将“使用 result 做更灵活的断言”改为“使用 result 更灵活地断言”。
🧰 Tools
🪛 LanguageTool
[uncategorized] ~99-~99: 动词的修饰一般为‘形容词(副词)+地+动词’。您的意思是否是:灵活"地"断言
Context: ...y.id); }); }); 使用 `result` 做更灵活的断言: typescript import assert from 'n...
(wb4)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/skills/egg-unittest/references/http-test.md` at line 99, 将第99行的句子“使用
`result` 做更灵活的断言”改为更符合语法的表述“使用 `result` 更灵活地断言”;在文件
packages/skills/egg-unittest/references/http-test.md 中定位该句并替换为新句子以保持语句流畅与一致性。
Summary
egg-controller, covering AOP (recommended) and function-style (legacy) patternsegg-unittestskill with 5 reference docs: HTTP test, Service/DI test, Mock patterns, BackgroundTask test, EventBus testegg/SKILL.md) routing for middleware and unittest queriesegg-controllerandegg-coreskills toegg-unittest@eggjs/skillspackage published files to skill directories onlyTest plan
npm pack --dry-runverify only skill dirs included🤖 Generated with Claude Code
Summary by CodeRabbit