我正在尝试测试api端点,以确保它们可以执行CRUD并在需要时发送安全错误。
我的问题是,我无法弄清楚如何在测试中接收正确的状态码和错误对象。
这是我所拥有的:
models / User.js
const UserSchema = new Schema({
username: {
type: String,
required: [true, 'username is required']
},
email: {
type: String,
required: [true, 'email is required']
},
password: {
type: String,
required: [true, 'password is required']
}
});
routes / api / users.js
users.post('/', urlencodedParser, (req, res, next) => {
let newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
newUser
.save()
.then(user => res.status(200).json(user))
.catch(err => next(err));
});
server.js
app.use((err, req, res, next) => {
if (err.name == 'ValidationError') {
let errors = {};
for (field in err.errors) {
errors[field] = err.errors[field].message;
}
res.status(400).json(errors);
}
});
routes.test.js
describe('Users', () => {
afterAll(() => {
app.close();
});
describe('CREATE', () => {
test('can create a user', () => {
return request(app)
.post('/api/users')
.send('username=johndoe&email=john@doe.com&password=123456')
.set('Accept', 'application/json')
.then(res => {
expect(res.statusCode).toBe(200);
expect(res.body.username).toBe('johndoe');
expect(res.body.email).toBe('john@doe.com');
expect(res.body.password).toBe('123456');
})
.catch(err => console.log(err));
});
test('can send errors', () => {
return request(app)
.post('/api/users')
.send('username=johndoe&password=123456')
.set('Accept', 'application/json')
.then(res => {
expect(res.statusCode).toBe(400);
// expect(res.body.email).toBe('Email is required')
})
.catch(err => console.log(err));
});
});
});
“可以发送错误”中的预期状态代码为400,但是接收到500。我最初的想法是错误对象位于req.body中,但是为空。
谢谢!