我有一条创造新车的途径。当在邮递员上进行测试时,但当我在其上运行MOCHA测试时,该路线可以正常工作。我收到的状态码为500,而不是预期的201。
我进行了一些故障排除,发现我的验证是导致此问题的原因,但我不知道在哪里
摩卡测试
describe('Car', () => {
it('should create a new vehicle item', (done) => {
const vehicle = {
state: 'new',
status: 'available',
price: 1200000,
manufacturer: 'honda',
model: 'accord',
bodyType: 'car',
};
chai.request(app)
.post('/api/v1/car')
.send(vehicle)
.end((err, res) => {
if (err) done(err);
const { body } = res;
expect(body).to.be.an('object');
expect(body.status).to.equal(201);
done();
});
});
});
const validateCarInput = (data) => {
const errors = {};
data.state = isEmpty(data.state) === true ? '' : data.state;
data.status = isEmpty(data.status) === true ? '' : data.status;
data.price = isEmpty(data.price) === true ? '' : data.price;
data.manufacturer = isEmpty(data.manufacturer) === true ? '' : data.manufacturer;
data.model = isEmpty(data.model) === true ? '' : data.model;
data.bodyType = isEmpty(data.bodyType) === true ? '' : data.bodyType;
if (!Validator.isAlpha(data.state)) {
errors.state = 'State must be in alphabet';
}
if (Validator.isEmpty(data.state)) {
errors.state = 'State of vehicle is required';
}
if (!Validator.isNumeric(data.price)) {
errors.price = 'price should be number and in this format (0.00)';
}
if (Validator.isEmpty(data.price)) {
errors.price = 'Price of vehicle is required';
}
if (!Validator.isAlpha(data.manufacturer)) {
errors.manufacturer = 'Manufacturer must be in alphabets';
}
if (Validator.isEmpty(data.manufacturer)) {
errors.manufacturer = 'Manufacturer of vehicle is required';
}
if (!Validator.isAlphanumeric(data.model)) {
errors.model = 'Model of vehicle can only be alphanumeric';
}
if (Validator.isEmpty(data.model)) {
errors.model = 'Model of vehicle is required';
}
if (!Validator.isAlpha(data.bodyType)) {
errors.bodyType = 'Body-type must be alphabets';
}
if (Validator.isEmpty(data.bodyType)) {
errors.bodyType = 'Body-type of vehicle is required';
}
return {
errors,
isValid: isEmpty(errors),
};
};
class carController {
static createCar(req, res) {
const { errors, isValid } = validateCarInput(req.body);
if (!isValid) {
return res.status(400).json({
errors
});
}
const vehicle = {
id: vehicles.length + 1,
userId: 3,
state: req.body.state,
status: 'available',
price: req.body.price,
manufacturer: req.body.manufacturer,
model: req.body.model,
bodyType: req.body.bodyType
};
vehicles.push(vehicle);
return res.status(201).json({
status: 201,
message: 'Vehicle created successfully',
data: vehicle,
});
}
我期望摩卡咖啡会抛出201状态代码,但我却收到500 我在用户路线上使用了类似的测试,而摩卡测试在该路线上运行正常