Step 20: Test users route

Let's update the corresponding tests in users.test.js to account for changes we made to users.js in the previous steps.

First, you must add role when you create a user. Exaple

const name = faker.name.fullName();
const email = faker.internet.email();
const password = faker.internet.password(6);
const role = Math.random() > 0.5 ? UserRole.Student : UserRole.Instructor;
const response = await request.post(endpoint).send({
  name,
  email,
  password,
  role,
});

Next, everywhere you expect a user object, you should assert it has a role attribute. Example:

expect(response.body.data.role).toBe(role);

Everywhere we can pass a role, we must check that it throws error for invalid ones. Example:

it("Invalid role", async () => {
  const name = faker.name.fullName();
  const email = faker.internet.email();
  const password = faker.internet.password(5);
  const role = faker.random.word();
  const response = await request.post(endpoint).send({
    name,
    email,
    password,
    role,
  });
  expect(response.status).toBe(400);
});

Next, when we create sample users, augment their user data with tokens to assist us in testing:

beforeEach(async () => {
  await userDao.deleteAll();
  users = [];
  for (let index = 0; index < numUsers; index++) {
    const name = faker.name.fullName();
    const email = faker.internet.email();
    const password = faker.internet.password(6);
    const role =
      index > numUsers / 2 ? UserRole.Student : UserRole.Instructor;
    const user = await userDao.create({ name, email, password, role });
    user.token = createToken({ user: { id: user.id, role: user.role } });
    user.expiredToken = createToken({
      user: { id: user.id, role: user.role },
      expiresIn: "0",
    });
    users.push(user);
  }
});

Next, when we make an authorized request, we must provide a token that results in successfull authorization. Example:

it("Respond 200", async () => {
  const response = await request
    .get(endpoint)
    .set(
      "Authorization",
      "bearer " + users.find((u) => u.role === UserRole.Instructor).token
    );
  expect(response.status).toBe(200);
  expect(response.body.data.length).toBe(numUsers);
});

Make sure to create requests with different user roles. Moreover, check for all cases where 403 or 401 errors would be throws. Example:

it("Respond 401 when expired auth token", async () => {
  const response = await request
    .get(endpoint)
    .set(
      "Authorization",
      "bearer " +
        users.find((u) => u.role === UserRole.Instructor).expiredToken
    );
  expect(response.status).toBe(401);
});

it("Respond 403", async () => {
  const response = await request
    .get(endpoint)
    .set(
      "Authorization",
      "bearer " + users.find((u) => u.role === UserRole.Student).token
    );
  expect(response.status).toBe(403);
});

Refer to the commit history to see the changes made at this step.