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?