Testing a Play Function with Jest
This challenge focuses on writing Jest tests for a play function that simulates a simple game. The function takes an array of numbers representing player scores and returns a boolean indicating whether a player has won the game based on a predefined winning score. This is a common scenario in game development and testing is crucial to ensure the game logic functions correctly.
Problem Description
You are given a play function (provided below) that determines if a player has won a game based on their score. The function accepts an array of numbers (scores) representing the player's scores and a number (winningScore) representing the score needed to win. The function should return true if the sum of the scores in the scores array is greater than or equal to the winningScore, and false otherwise.
Your task is to write a suite of Jest tests to thoroughly test the play function. Your tests should cover:
- Positive Cases: Scenarios where the sum of scores is greater than or equal to the winning score.
- Negative Cases: Scenarios where the sum of scores is less than the winning score.
- Edge Cases:
- An empty
scoresarray. - A
winningScoreof 0. - A
winningScoreequal to the sum of the scores.
- An empty
- Invalid Input: While not strictly required, consider how the function should behave if the input is invalid (e.g.,
scorescontains non-numeric values). You can choose to either test for this behavior or assume the input will always be valid.
Examples
Example 1:
Input: scores = [1, 2, 3], winningScore = 5
Output: true
Explanation: The sum of the scores (1 + 2 + 3 = 6) is greater than the winning score (5).
Example 2:
Input: scores = [1, 2, 3], winningScore = 10
Output: false
Explanation: The sum of the scores (1 + 2 + 3 = 6) is less than the winning score (10).
Example 3:
Input: scores = [], winningScore = 0
Output: false
Explanation: The sum of an empty array is 0, which is not greater than the winning score of 0.
Example 4:
Input: scores = [5, 5], winningScore = 10
Output: true
Explanation: The sum of the scores (5 + 5 = 10) is equal to the winning score (10).
Constraints
- The
scoresarray will contain only numbers (integers or floats). - The
winningScorewill be a number (integer or float). - The length of the
scoresarray can be any non-negative integer. - The
winningScorecan be any non-negative number.
Notes
- You are provided with the
playfunction. Do not modify it. - Focus on writing clear, concise, and well-documented Jest tests.
- Consider using
describeanditblocks to organize your tests logically. - Use Jest's assertion methods (e.g.,
expect(result).toBe(true)) to verify the expected behavior. - Think about the different scenarios and edge cases that could arise and write tests to cover them.
// play.ts (Provided - DO NOT MODIFY)
export function play(scores: number[], winningScore: number): boolean {
const sum = scores.reduce((acc, score) => acc + score, 0);
return sum >= winningScore;
}