CPSC270
Software Engineering and Project Design

Activity 27

Testing - Jest Async

Write Jest tests for the get method:

class Users {
  /** {string: number} database of users and counts **/
  static users = {};

  /**
   * Add a user and associated count to the database.
   * @param {string} userName - name of user to add.
   * @throws Error if userName is already in database.
   */
  static add(userName, count) {
    if (!this.users.hasOwnProperty(userName)) {
      this.users[userName] = count;
    } else {
      throw Error(`${userName} already exists`);
    }
  }

  /**
   * Remove a user from the database.
   * @param {string} userName - name of user to remove.
   * @throws Error if userName is not in database.
   */
  static remove(userName) {
    if (this.users.hasOwnProperty(userName)) {
      delete this.users[userName];
    } else {
      throw Error(`${userName} does not exist`);
    }
  }

  /**
   * Get a user's count.
   * @param {string} userName - user's name.
   * @return {number} The user's count.
   */
  static get(userName) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (this.users.hasOwnProperty(userName)) {
          resolve(this.users[userName]);
        } else {
          reject(`${userName} does not exist`);
        }
      }, 100);
    });
  }
}

module.exports = Users;