账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    eggjs做单元测试时session问题
    42
    0

    在eggjs中写单元测试代码如下`class HomeController extends Controller {
    async index() {

    this.ctx.session = { data: 'coook-test ----------------'} 
    console.log(this.ctx.session);
    this.ctx.body = 'hi, egg';

    }
    async getSession() {

    console.log(this.ctx.session);
    this.ctx.body = 'hi, egg'

    }

    }`
    home.test.js中
    ` it('should GET /', () => {

    const result = app.httpRequest(app)
      .get('/')
      .expect('hi, egg')
      .expect(200)
      .end((err, res) => {
        console.log(res.text);
      });    

    });
    it('should GET /getSession', () => {

    const result = app.httpRequest(app)
      .get('/getSession')
      .expect('hi, egg')
      .expect(200)
      .end((err, res) => {
        console.log(res.text);
      });

    });`
    测试在controller中的console.log(this.ctx.session)为空
    想请问下在egg测试中怎么去保存session会话,找了很久还是没找到
    求帮助……

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 稚与最初 普通会员 1楼

      在 Egg.js 中,你可以在一个测试文件中模拟 session。以下是一个简单的示例:

      首先,你需要创建一个 session 存储模块:

      javascript var session = require('./session');

      然后,你可以创建一个测试文件,如 test_session.js,并在其中创建一个 session 。

      javascript describe('session', function() { it('should store and retrieve session', function() { session.set('key', 'value'); expect(session.get('key')).toBe('value'); session.clear(); expect(session.get('key')).toBeUndefined(); }); });

      在这个测试中,我们首先设置一个 session,然后测试它的存储和检索功能。如果 setget 方法都能正确工作,那么我们就说 session 已经被正确地存储和检索了。

      请注意,你需要在你的项目的eggjs配置文件中启用 session。例如,如果你使用的是 @eggjs/core,你需要添加以下配置:

      javascript module.exports = { session: { store: { set: function(key, value) { // ... }, get: function(key) { // ... } } } };

      在上述代码中,store 是 session 存储模块的实例,setget 方法分别用于设置和获取 session 中的键值对。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部