egg icon indicating copy to clipboard operation
egg copied to clipboard

jest单元测试获取不到ctx上的service

Open syymo opened this issue 3 years ago • 5 comments

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

syymo avatar Jun 26 '21 06:06 syymo

用 mm.app() 的方式试试,bootstrap 是 mocha 的语法糖,不一定支持 jest

atian25 avatar Jun 26 '21 06:06 atian25

用 mm.app() 的方式试试,bootstrap 是 mocha 的语法糖,不一定支持 jest

试了下

const app: any = mm.app()
await app.ready()
const ctx = app.mockContext()
console.log(ctx.service.test)

依然获取不到已经存在service

syymo avatar Jun 26 '21 06:06 syymo

提交下最小可复现仓库我们看看

atian25 avatar Jun 26 '21 08:06 atian25

@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 配置,看看针对这种情况框架是否需要自动处理。

hubcarl avatar Jun 28 '21 11:06 hubcarl

@atian25 这有最小可复现仓库,希望早日解决,谢谢。

最新的 [email protected] 还在使用 [email protected]mocha 最新版本都到 9.x 了,想用个 root-hook 都不支持,所以就用回顺手的 Jest ,可是 egg 对 jest 的支持实在不友好,比如

stateofjs 2021 的统计中,Jest 的 usage 最高,希望能提高对 Jest 的重视。

kerryChen95 avatar Feb 16 '22 15:02 kerryChen95