[eggjs/egg]egg test 返回的信息和egg-validate 返回的信息不一致

2025-11-20 47 views
1
  • Node Version:v8.7.0
  • Egg Version:v2.12.0
  • Plugin Name:egg-validate
  • Plugin Version:2.0.2
  • Platform:macos
  • Mini Showcase Repository:

在对controller中的文件写测试用例的时候,对于常见比如说登录这一块,比如验证邮箱没填写,egg-validate 对其进行校验时,返回的状态码是422,这个和在测试文件的结果一致,但是返回的数据两者有差异,我贴个截图吧

回答

2

app/controller/user.js

 const paramRule = {
      email: {
        type: 'string',
        required: true
      },
      password: {
        type: 'string',
        required: true
      },
    };
    // 校验参数email和密码
    let paramObj = {
      email: email,
      password: password,
    };
    const paramErrors = this.app.validator.validate(paramRule, paramObj);
    if (!_.isArray(emailErrors)) {
        //...
    }else{
          ctx.body = paramErrors;
          ctx.status = 422;
    }

test/controller/user.test.js

const { app } = require('egg-mock/bootstrap');
describe('login()', () => {
    it('without email should status 422 and get the response body', () => {
        return app.httpRequest()
            .post('/user/login')
            .type('form')
            .send({
                // email: 'jxycbjhc@163.com',
                password: '123456',
            })
            .expect(422)
            .expect([{
                "message": "should not be empty",
                "code": "invalid",
                "field": "email"
            }]);
    });
     it('without password should status 422 and get the response body', () => {
        return app.httpRequest()
            .post('/user/login')
            .type('form')
            .send({
                email: 'jxycbjhc@163.com',
               //password: '123456',
            })
            .expect(422)
            .expect([{
                "message": "should not be empty",
                "code": "invalid",
                "field": "password"
            }]);
    });
});
1

egg-init --type=simple 初始化个最小可复现仓库,然后提交到你的 GitHub 吧

7

看了一下,测试用例好像不对?参考下面的测试用例。

3

@thonatos 不是太明白,这个是对egg-validate模块的测试文件,我想表达的是egg-validate模块提供的报错和在测试文件下的报错是不一致的。

6

@jxycbjhc

跑了你提供的代码,结果也确实和截图一样。

但是问题是,此处并没有按照 egg-validate 文档使用,使用问题请参考egg-validate文档。