Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Jay Azares
16,600 PointsGetting this error in Mocha testing: TypeError: Cannot read property 'filter' of undefined
Here's my code....am I missing something?
JAVASCRIPT:
function checkForShip (player, coordinates) { var shipPresent, ship;
for (var i = 0; i < player.ships.length; i++) {
ship = player.ships[i];
shipPresent = ship.locations.filter(function (actualCoordinate) {
return (actualCoordinate[0] === coordinates[0]) && (actualCoordinate[1] === coordinates[1]);
})[0];
if (!shipPresent) {
return false;
} else {
return true;
}
}
}
module.exports.checkForShip = checkForShip;
MOCHA:
Mocha √ should run our tests using npm
checkForShip 1) should correctly report no ship at a given players coordinate 2) should correctly report a ship located at the given coordinates 3) should handle ships at more than one coordinate
1 passing (18ms) 3 failing
1) checkForShip should correctly report no ship at a given players coordinate: TypeError: Cannot read property 'filter' of undefined at checkForShip (game_logic\ship_methods.js:7:37) at Context.<anonymous> (test\ship_test.js:16:16)
2) checkForShip should correctly report a ship located at the given coordinates: TypeError: Cannot read property 'filter' of undefined at checkForShip (game_logic\ship_methods.js:7:37) at Context.<anonymous> (test\ship_test.js:29:16)
3) checkForShip should handle ships at more than one coordinate: TypeError: Cannot read property 'filter' of undefined at checkForShip (game_logic\ship_methods.js:7:37) at Context.<anonymous> (test\ship_test.js:41:16)
2 Answers

Up&Up Agency
Courses Plus Student 8,063 PointsIt is likely due to the structure of your player
object. The JS interpreter cannot run the filter()
function on something that is not an array.
Check the player object you are passing into the function and make sure that player.ships
is an array of location objects that contain an array of locations.

jennyhan
36,121 PointsIt should because that you didn't define the ship object correctly. Did you create a player object exactly like this:
player = {
ships: [
{
locations: [[0, 0]]
}
]
};