Step 3: Tests

The starter comes with extensive suit of tests. However, the tests are not comperhensive. I intentionally missed some! Run the tests with coverage to find what tests are missing!

No test for query parameters!

We can update UserDao.test.js and add the following:

it("test readAll() given a name", async () => {
  const index = Math.floor(Math.random() * numUsers);
  const user = users[index];
  const _users = await userDao.readAll({ name: user.name });
  expect(_users.length).toBeGreaterThanOrEqual(1);
});

it("test readAll() given a email", async () => {
  const index = Math.floor(Math.random() * numUsers);
  const user = users[index];
  const _users = await userDao.readAll({ email: user.email });
  expect(_users.length).toBeGreaterThanOrEqual(1);
});

Note: We should also add such tests for testing /users route.

No test for invalid attributes when updating a user document!

We can update UserDao.test.js and add the following:

it("test update() given invalid name", async () => {
  try {
    const index = Math.floor(Math.random() * numUsers);
    const user = users[index];
    const name = "";
    await userDao.update({
      id: user.id,
      name,
    });
  } catch (err) {
    expect(err.status).toBe(400);
  }
});

it("test update() given invalid email", async () => {
  try {
    const index = Math.floor(Math.random() * numUsers);
    const user = users[index];
    const email = faker.name.fullName();
    const _user = await userDao.update({
      id: user.id,
      email,
    });
  } catch (err) {
    expect(err.status).toBe(400);
  }
});

Note: We should also add such tests for testing /users route.

When writing the tests above, you will find an error in UserDao.update:

    debug("Validating the name..");
    result = validName.safeParse(name);
-   if (name && !result.success) {
+   if (name !== undefined && !result.success) {
      throw new ApiError(400, "Invalid Name!");
    }

No test for unique email!

The code coverage does not show that we are missing tests for the requirement that user email must be unique! We can add the following test to User.test.js

it("test email is not unique", async () => {
  try {
    let name = faker.name.fullName();
    const email = faker.internet.email();
    await User.create({ name, email });

    name = faker.name.fullName();
    await User.create({ name, email });
  } catch (err) {
    expect(err).toBeDefined();
  }
});

Important: We must update UserDao to account for this and throw appropriate ApiError. Moreover, we must update the corresponding tests for DAO and routes.

Refer to the commit history to see the changes made at this step to get desired test coverage.