egg
egg copied to clipboard
jest单元测试获取不到ctx上的service
What happens?
jest写单元测试 egg-mock/bootstrap
里面的ctx获取不到service
最小可复现仓库
import { Context } from 'egg';
import { app } from 'egg-mock/bootstrap';
describe('common tset', () => {
it('get list', async () => {
let ctx: Context = app.mockContext();
console.log(ctx.service.test) // undefined
})
})
复现步骤,错误日志以及相关配置
let ctx: Context = app.mockContext(); console.log(ctx.service.test) // undefined 获取不到srvice等信息,有什么办法解决吗?
相关环境信息
- 操作系统:MacOS
- Node 版本:10.24
- Egg 版本:2.6.1
用 mm.app() 的方式试试,bootstrap 是 mocha 的语法糖,不一定支持 jest
用 mm.app() 的方式试试,bootstrap 是 mocha 的语法糖,不一定支持 jest
试了下
const app: any = mm.app()
await app.ready()
const ctx = app.mockContext()
console.log(ctx.service.test)
依然获取不到已经存在service
提交下最小可复现仓库我们看看
@sdjdd 需要配置在跑 jest 的前面配置 EGG_TYPESCRIPT= true 环境变量, 比如 package.json 的 script 命令
"scripts": {
"jest": "EGG_TYPESCRIPT=true jest"
}
原因是因为 EGG_TYPESCRIPT 变量在 egg 体系里面是通过 egg-bin 自动注入的, 非 egg-bin 导致这个 EGG_TYPESCRIPT 环境变量没有,最后走 js 加载逻辑(https://github.com/eggjs/egg-core/blob/master/lib/loader/file_loader.js#L125),也也就出现没有挂载 service 的问题
@atian25 本身 typescript 项目里面 package.json 有 egg.typescript = true 配置,看看针对这种情况框架是否需要自动处理。
@atian25 这有最小可复现仓库,希望早日解决,谢谢。
最新的 [email protected]
还在使用 [email protected]
, mocha
最新版本都到 9.x
了,想用个 root-hook 都不支持,所以就用回顺手的 Jest ,可是 egg 对 jest 的支持实在不友好,比如
- 没能开箱可用。
- 这个 unittest-ject 示例都还是基于
[email protected]
的, -
egg-core中对于jest的测试用例 也没包含这个issue中提到的
ctx.service.xxx
没注入的case。
stateofjs 2021 的统计中,Jest 的 usage 最高,希望能提高对 Jest 的重视。