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"
}]);
});
});