所以我有一个带有中间件的控制器。但我不知道如何用玩笑来测试它。香港专业教育学院阅读的所有示例都是不同的。像这样的link
export class UsersController extends BaseController {
@Post('signup')
@Middleware([UserMiddleware.validateUser, UserMiddleware.generateTokenUsingJWT])
private async userSignUp(req: Request, res: Response) {
const { user, jwt } = res.locals;
try {
res.json({
meta: {},
payload: {
user: {
username: user.username
},
jwt
}
});
} catch (error) {
res.json({
error
});
}
}
}
中间件:
export class UserMiddleware {
static async validateUser(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
// if validation fail lets hope it throws.
const user: User = await User.create({
...req.body
}).validateModel();
res.locals = {
user: await user.save()
};
next();
} catch (error) {
res.json({
error
});
}
}
static async checkUserBeforeLogin(req: Request, res: Response, next: NextFunction): Promise<void> {
const { email, password } = req.body;
try {
const user = await User.findOneOrFail({ select: ['id', 'email', 'password'], where: { email } });
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (isPasswordCorrect) {
res.locals = {
user
};
next();
} else {
res.json({
error: 'incorrect password'
});
}
} catch (error) {
res.status(404).json({
error: `no user with ${email}`
});
}
}
static generateTokenUsingJWT(req: Request, res: Response, next: NextFunction): void {
const { user } = res.locals;
const { id, email } = user;
const jwt = JwtManager.jwt({
id,
email
});
if (jwt) {
res.locals = {
jwt,
user
};
next();
} else {
res.status(500).json({
error: 'Can not generate token'
});
}
}
}
我被困在这一个上
describe('', () => {
it('should validate a user', async () => {
const req = {
body: {
username: 'nocap',
email: 'nocap@gmail.com',
password: 'password'
}
};
const res = {
locals: {}
};
const result = await new Promise((response, reject) => {
UserMiddleware.validateUser(req, res, (err) => {
if (!err) {
response(resp);
}
});
});
expect(true).toBe(true);
});
});
测试尚未完成。我不知道从哪里获取参数。即时通讯收到类型错误。有任何想法吗?谢谢。圣诞快乐