From cac2bd30e23d2f2d4835802afc120e4b70ca7a15 Mon Sep 17 00:00:00 2001 From: Maciej Matuszczak Date: Mon, 17 Feb 2020 09:50:18 +0100 Subject: [PATCH] [#121] Added validation of postCode --- src/db/models/school.js | 8 +++++++- src/test/models/school_model.test.js | 21 +++++++++++++++------ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/db/models/school.js b/src/db/models/school.js index caee5fc..3beaf86 100644 --- a/src/db/models/school.js +++ b/src/db/models/school.js @@ -22,7 +22,13 @@ const School = sequelize.define( }, postCode: { type: Sequelize.STRING(6), - allowNull: false + allowNull: false, + validate: { + isValidaPolishPostCode(value) { + const regex = /^[0-9]{2}-[0-9]{3}$/; + if (!regex.test(value)) throw new Error("Invalid polish postal code"); + } + } }, postOffice: { type: Sequelize.STRING(80), diff --git a/src/test/models/school_model.test.js b/src/test/models/school_model.test.js index bc99ccf..63dd2bf 100644 --- a/src/test/models/school_model.test.js +++ b/src/test/models/school_model.test.js @@ -5,7 +5,7 @@ const { schoolData } = require("../factories/schoolFactory"); const { School } = require("../../db/models"); describe("School model", () => { - beforeAll(() => { + beforeEach(() => { return sequelize .sync({ force: true }) .then(() => schoolTypeFactory("mock")); @@ -22,11 +22,20 @@ describe("School model", () => { expect(school.name).toEqual("TEST"); }); - // it("should validate `postCode`", () => { - // const school = await sequelize - // .sync({ force: true }) - // .then(() => schoolFactory({ name: "TEST", type: "przedszkole" })); - // }) + it("should validate `postCode`", async () => { + const school = await sequelize + .sync({ force: true }) + .then(() => + schoolFactory({ + type: "mock", + postCode: "invalid code", + SchoolTypeName: "mock" + }) + ) + .catch(err => err.message); + + expect(school).toEqual("Validation error: Invalid polish postal code"); + }); describe("has virtual methods which", () => { it("return concatenated address data by calling `address`", async () => {