Step 14: Add a role
We will have two kinds of users: instructors and studetns.
Let's create a UserRole.js
file in the src/model
folder:
export const UserRole = {
Student: "STUDENT",
Instructor: "INSTRUCTOR",
};
Next, add a role
attribute to User
schema:
role: {
type: String,
enum: Object.values(UserRole),
required: true,
default: UserRole.Student,
},
Notice the default
attribute; if a role was not specified, the user will be
give the student role by default.
Update Tests
We should update the tests in tests/mode/User.test.js
.
-
Everywhere we create a user, we can provide a role (or leave it to fall back to default role)
const role = Math.random() > 0.5 ? UserRole.Student : UserRole.Instructor; const user = await User.create({ name, email, password, role });
-
Everywhere we check user attributes, we must check for the role attribute.
expect(user.role).toBe(role);
-
When creating a user, we must have a test where we provide the role and another where it falls back to default
it("test create user with default role", async () => { const name = faker.name.fullName(); const email = faker.internet.email(); const password = faker.internet.password(); const user = await User.create({ name, email, password }); expect(user.name).toBe(name); expect(user.email).toBe(email); expect(user.id).toBeDefined(); expect(user.password).toBe(password); expect(user.role).toBe(UserRole.Student); });
-
We need to add tests for invalid or missing
role
!describe("test role is required", () => { it("test role is null", async () => { /* not shown */ }); it("test role is undefined", async () => { /* not shown */ }); it("test role is empty", async () => { /* not shown */ }); it("test role is invalid", async () => { try { const name = faker.name.fullName(); const email = faker.internet.email(); const password = faker.internet.password(); const role = faker.random.word(); await User.create({ name, email, password, role }); } catch (err) { expect(err).toBeDefined(); } }); });
Refer to the commit history to see the changes made at this step.