Before getting any further, let’s recall some good TDD practices:

  • make your tests expressive by writing them in four phases
  • make your tests isolated with setup and teardown phases
  • follow the red, green, refactor cycle

In this lesson you will be writing your setup and teardown phases in beforeEach and afterEach hooks provided by Mocha.

Before each test, your beforeEach hook will connect to the database and drop any old data using these method calls:

await mongoose.connect(databaseUrl, options); await mongoose.connection.db.dropDatabase();

After each test, your afterEach hook will disconnect from the database with

await mongoose.disconnect();

You can refactor these hooks by wrapping the three calls in two helper functions: connectAndDrop and disconnect. In your test file, import those functions and add them to your hooks.



A #save test has been added to further drive development. Run the tests by entering npm test in the terminal.


You should get a Timeout error — Mocha is waiting for a connection that doesn’t exist yet. Add this under the first describe:

beforeEach( async () => { await mongoose.connect(databaseUrl, options); }); afterEach( async () => { await mongoose.disconnect; });

Run the tests and see green.


Run the tests again and see red!

AssertionError: expected 2 to equal 1

This error is telling you that there are 2 documents found, when 1 was expected. Your test is not isolated — the document added in the previous test run still exists in the database.


In the beforeEach hook after the call to connect, add

await mongoose.connection.db.dropDatabase();

This drops any old data in the database.


Run the test suite and see green!


Time to refactor. The two helper functions connectAndDrop and disconnect have been defined for you in database.js. Import the functions at the top of dinosaur-test.js by replacing {mongoose, databaseUrl, options} with {connectAndDrop, disconnect}.


Delete the contents of the beforeEach hook, including async () => {...}.

Pass the argument connectAndDrop to the beforeEach function.


Delete the contents of the afterEach hook, including async () => {...}.

Pass the argument disconnect to the afterEach function.


Run the tests to confirm that you’re still in the green.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?