3
06/11/2024 6:16 pm
Topic starter
Write Mocha tests to verify the functionality of the following JS code:
class SortedList { constructor() { this.list = []; } add(element) { this.list.push(element); this.sort(); } remove(index) { this.vrfyRange(index); this.list.splice(index, 1); } get(index) { this.vrfyRange(index); return this.list[index]; } vrfyRange(index) { if (this.list.length == 0) throw new Error("Collection is empty."); if (index < 0 || index >= this.list.length) throw new Error("Index was outside the bounds of the collection."); } sort() { this.list.sort((a, b) => a - b); } get size() { return this.list.length; } }
Your tests will be supplied with a class named SortedList. It needs to meet the following requirements:
- Maintains a collection of numeric elements
- Has an add(element) function, which adds a new element to the collection
- Has a remove(index) function, which removes the element at position index
- Has a get(index) function, which return the value of the element at position index
- Keeps the elements of the collection sorted in ascending order at all times
- Throws an error if the functions get() and remove() are supplied with an invalid index (negative or outside the collection) or if the collection is empty
- Has a size() property getter, which returns the number of elements inside the collection
1 Answer
2
06/11/2024 6:18 pm
First you need to write down the requirements for the tests:
Test initial state: --add exists --remove exists --get exists --size exists add(): --add 1 element --add many elements remove(): --test if list is empty (should throw error: "Collection is empty") --test negative number(index) (should throw error: "Index was outside the bounds of the collection.") --test if index is equal to list length (should throw error: "Index was outside the bounds of the collection.") --test if index is bigger than list length (should throw error: "Index was outside the bounds of the collection.") --test with correct index (element should be removed) get() (almost the same as remove()): --test if list is empty (should throw error) --test negative number (should throw error) --test if index is equal tp list length (should throw error) --test if index is bigger than list length (should throw error) --test with correct index (should return the correct element) size(): --empty list --list with elements
Here is the JavaScript file with the tests inside: see here
Only the Mocha + Chai tests: see here