Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Unit Testing Behavior Driven Development with Mocha & Chai Writing Our First Test Suite - Part 2

Jay Azares
Jay Azares
16,600 Points

Getting 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
PLUS
Up&Up Agency
Courses Plus Student 8,063 Points

It 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
jennyhan
36,121 Points

It 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]]
        }
      ]
    };