Learn
Model Testing Patterns
Hooks

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.

Instructions

1.

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

2.

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; });
3.

Run the tests and see green.

4.

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.

5.

In the beforeEach hook after the call to connect, add

await mongoose.connection.db.dropDatabase();

This drops any old data in the database.

6.

Run the test suite and see green!

7.

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}.

8.

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

Pass the argument connectAndDrop to the beforeEach function.

9.

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

Pass the argument disconnect to the afterEach function.

10.

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

Folder Icon

Sign up to start coding

Already have an account?