Egg: Middleware Unit Test

Created on 17 Jan 2018  ·  11Comments  ·  Source: eggjs/egg

  • Node Version:
  • Egg Version:
  • Plugin Name:
  • Plugin Version:
  • Platform:
  • Mini Showcase Repository:

请问官方有提供 middleware 的单元测试例子吗?我在官网文档上并未查找到相关的文档。

https://eggjs.org/zh-cn/core/unittest.html

All 11 comments

就正常 app.httpRequest 那样测试咯,有什么问题么?

比如我的业务是这样的

//  app/router.js

const test = app.middleware.test(options);
router.get('/test', test, 'controller1', '...');

那假如我直接在测试中:

//  test/app/middleware/test.test.js
app.httpRequest('/test');

这样不是就不仅测试middleware, 并且还涉及到 controller 层的逻辑了。
我以为会是像 Service 那样进行测试。

或者说 middleware 的测试一直就是和 controller 结合在一起的吗?

真想测试的话,办法还是不少的:

  • mock controller (要看下 koa-router 源码,因为 Controller 注册到 Router 后,再 mock app.controller 已经晚了,可能要 mock router 对象里面的值)
  • 在 test 里面声明额外的 router,特殊的 Controller 挂载这个 middleware 然后测试。
  • 直接 app.middleware.xx(options, app) 这种方式来实例化,然后调用测试。

@atian25 hello, 请问我的 router 是这样的,假如我想测 controller1 , 我能 mock 掉 middleware test 吗?

//  app/router.js

const test = app.middleware.test(options);
router.get('/test', test, 'controller1');

在 test 里面声明一个 router.get('/testxxx', 'controller1'); 来测试咯

@atian25 OK,thanks

@atian25 好像不行,不知道我是否写得正确

beforeEach(() => {
  const { router, controller } = app;
  router.get('/test/xxxx', async (ctx, next) => ctx.somekey = 2333, controller.index.get);
})
afterEach(mock.restore);

it('test', async () => {
  const res = app.httpRequest()
    .get('/test/xxxx');

  //  test controller
});

async (ctx, next) => ctx.somekey = 2333 没有 await next 啊

@atian25 恩,我刚才把这个最小的例子放到我的测试里面发现不报错 :cry: . 十分感谢。

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zrxisme picture zrxisme  ·  44Comments

killagu picture killagu  ·  48Comments

popomore picture popomore  ·  38Comments

kkys4bfgp75be9p picture kkys4bfgp75be9p  ·  36Comments

jtyjty99999 picture jtyjty99999  ·  52Comments