Reputation: 2503
I have the following model:
const mongoose = require("mongoose");
const Joi = require("@hapi/joi");
const activitySchema = new mongoose.Schema({
title: {
type: String,
maxlength: 255,
minlength: 3,
required: true
}
});
const Activity = mongoose.model("Activity", activitySchema);
function validateActivity(activity) {
const schema = Joi.object({
title: Joi.string().min(3).max(255).required()
});
return schema.validate(activity)
}
module.exports.Activity = Activity;
module.exports.validate = validateActivity;
And I'm writing a unit test for the validateActivity function. I am not sure about what's the best practice for writing these tests.
So far I came up with:
const {validateActivity} = require("../../models/activity");
describe("activity model", () => {
let mockActivity;
beforeEach(() => {
mockActivity = {
title: "123"
}
});
it("should return an error if no title is provided", () => {
delete mockActivity.title;
const result = validateActivity(mockActivity);
expect(result.error.details[0].type).toMatch(/any.required/);
});
it("should return an error if title is not a string", () => {
mockActivity.title = { test: "test" };
const result = validateActivity(mockActivity);
expect(result.error.details[0].type).toMatch(/string.base/);
});
it("should return an error if title is less than 3 chars", () => {
mockActivity.title = "12";
const result = validateActivity(mockActivity);
expect(result.error.details[0].type).toMatch(/string.min/);
});
it("should return an error if title is more than 255 chars", () => {
mockActivity.title = Array(258).join("a");
const result = validateActivity(mockActivity);
expect(result.error.details[0].type).toMatch(/string.max/);
});
});
So once I add several fields to my model the testing will be quite repetitive. Is it necessary to write a test for each scenario?
Upvotes: 1
Views: 2746
Reputation: 7770
I guess it all depends on how strict and important you want your validation to be. If you have a data centric application where your bread and butter is data. if you don't test your data thoroughly you might end up in a bad situation.
Now imagine in your case you have a schema amd you don't have tests. If you for example remove max(255)
condition, your all tests will pass (since you don't have any) and your customers will be able to insert data which is longer than 255 which obviously will be wrong.
I don't see any thing wrong in what you are doing. You can consider grouping stuff when you have multiple fields. In nutshell, you should test your schema thoroughly if data integrity is super important for you.
Upvotes: 1
Reputation: 2503
After viewing this comment https://stackoverflow.com/a/33588497/5733078 it seems that it would not make sense to check every scenario since we can trust that the validate function has already been tested within Joi.
Upvotes: 0